diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift index a7a128f638..a9b2108e64 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift @@ -11,22 +11,26 @@ import AWSPluginsCore extension AWSDataStorePlugin: DataStoreBaseBehavior { // MARK: - Save - public func save(_ model: M, - where condition: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) { + public func save( + _ model: M, + where condition: QueryPredicate? = nil, + completion: @escaping DataStoreCallback + ) { save(model, modelSchema: model.schema, where: condition, completion: completion) } - public func save(_ model: M, - where condition: QueryPredicate? = nil) async throws -> M { + public func save( + _ model: M, + where condition: QueryPredicate? = nil + ) async throws -> M { try await save(model, modelSchema: model.schema, where: condition) } public func save( _ model: M, - modelSchema: ModelSchema, - where condition: QueryPredicate? = nil, - completion: @escaping DataStoreCallback + modelSchema: ModelSchema, + where condition: QueryPredicate? = nil, + completion: @escaping DataStoreCallback ) { log.verbose("Saving: \(model) with condition: \(String(describing: condition))") let prepareSaveResult = initStorageEngineAndTryStartSync().flatMap { storageEngineBehavior in @@ -57,9 +61,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func save(_ model: M, - modelSchema: ModelSchema, - where condition: QueryPredicate? = nil) async throws -> M { + public func save( + _ model: M, + modelSchema: ModelSchema, + where condition: QueryPredicate? = nil + ) async throws -> M { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in save(model, modelSchema: model.schema, where: condition) { result in continuation.resume(with: result) @@ -70,9 +76,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { // MARK: - Query @available(*, deprecated, renamed: "query(byIdentifier:completion:)") - public func query(_ modelType: M.Type, - byId id: String, - completion: DataStoreCallback) { + public func query( + _ modelType: M.Type, + byId id: String, + completion: DataStoreCallback + ) { let predicate: QueryPredicate = field("id") == id query(modelType, where: predicate, paginate: .firstResult) { switch $0 { @@ -89,8 +97,10 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } @available(*, deprecated, renamed: "query(byIdentifier:)") - public func query(_ modelType: M.Type, - byId id: String) async throws -> M? { + public func query( + _ modelType: M.Type, + byId id: String + ) async throws -> M? { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in query(modelType, byId: id) { result in continuation.resume(with: result) @@ -98,49 +108,69 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func query(_ modelType: M.Type, - byIdentifier identifier: String, - completion: DataStoreCallback) where M: ModelIdentifiable, + public func query( + _ modelType: M.Type, + byIdentifier identifier: String, + completion: DataStoreCallback + ) where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { - queryByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: DefaultModelIdentifier.makeDefault(id: identifier), - completion: completion) + queryByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: DefaultModelIdentifier.makeDefault(id: identifier), + completion: completion + ) } - public func query(_ modelType: M.Type, - byIdentifier identifier: String) async throws -> M? + public func query( + _ modelType: M.Type, + byIdentifier identifier: String + ) async throws -> M? where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { - try await queryByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: DefaultModelIdentifier.makeDefault(id: identifier)) + try await queryByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: DefaultModelIdentifier.makeDefault(id: identifier) + ) } - public func query(_ modelType: M.Type, - byIdentifier identifier: ModelIdentifier, - completion: DataStoreCallback) where M: ModelIdentifiable { - queryByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: identifier, - completion: completion) + public func query( + _ modelType: M.Type, + byIdentifier identifier: ModelIdentifier, + completion: DataStoreCallback + ) where M: ModelIdentifiable { + queryByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: identifier, + completion: completion + ) } - public func query(_ modelType: M.Type, - byIdentifier identifier: ModelIdentifier) async throws -> M? + public func query( + _ modelType: M.Type, + byIdentifier identifier: ModelIdentifier + ) async throws -> M? where M: ModelIdentifiable { - try await queryByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: identifier) - } - - private func queryByIdentifier(_ modelType: M.Type, - modelSchema: ModelSchema, - identifier: ModelIdentifierProtocol, - completion: DataStoreCallback) { - query(modelType, - modelSchema: modelSchema, - where: identifier.predicate, - paginate: .firstResult) { + try await queryByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: identifier + ) + } + + private func queryByIdentifier( + _ modelType: M.Type, + modelSchema: ModelSchema, + identifier: ModelIdentifierProtocol, + completion: DataStoreCallback + ) { + query( + modelType, + modelSchema: modelSchema, + where: identifier.predicate, + paginate: .firstResult + ) { switch $0 { case .success(let models): do { @@ -155,9 +185,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - private func queryByIdentifier(_ modelType: M.Type, - modelSchema: ModelSchema, - identifier: ModelIdentifierProtocol) async throws -> M? { + private func queryByIdentifier( + _ modelType: M.Type, + modelSchema: ModelSchema, + identifier: ModelIdentifierProtocol + ) async throws -> M? { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in queryByIdentifier(modelType, modelSchema: modelSchema, identifier: identifier) { result in continuation.resume(with: result) @@ -165,28 +197,36 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func query(_ modelType: M.Type, - where predicate: QueryPredicate? = nil, - sort sortInput: QuerySortInput? = nil, - paginate paginationInput: QueryPaginationInput? = nil, - completion: DataStoreCallback<[M]>) { - query(modelType, - modelSchema: modelType.schema, - where: predicate, - sort: sortInput?.asSortDescriptors(), - paginate: paginationInput, - completion: completion) + public func query( + _ modelType: M.Type, + where predicate: QueryPredicate? = nil, + sort sortInput: QuerySortInput? = nil, + paginate paginationInput: QueryPaginationInput? = nil, + completion: DataStoreCallback<[M]> + ) { + query( + modelType, + modelSchema: modelType.schema, + where: predicate, + sort: sortInput?.asSortDescriptors(), + paginate: paginationInput, + completion: completion + ) } - public func query(_ modelType: M.Type, - where predicate: QueryPredicate? = nil, - sort sortInput: QuerySortInput? = nil, - paginate paginationInput: QueryPaginationInput? = nil) async throws -> [M] { - try await query(modelType, - modelSchema: modelType.schema, - where: predicate, - sort: sortInput?.asSortDescriptors(), - paginate: paginationInput) + public func query( + _ modelType: M.Type, + where predicate: QueryPredicate? = nil, + sort sortInput: QuerySortInput? = nil, + paginate paginationInput: QueryPaginationInput? = nil + ) async throws -> [M] { + try await query( + modelType, + modelSchema: modelType.schema, + where: predicate, + sort: sortInput?.asSortDescriptors(), + paginate: paginationInput + ) } public func query( @@ -213,11 +253,13 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func query(_ modelType: M.Type, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - sort sortInput: [QuerySortDescriptor]? = nil, - paginate paginationInput: QueryPaginationInput? = nil) async throws -> [M] { + public func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + sort sortInput: [QuerySortDescriptor]? = nil, + paginate paginationInput: QueryPaginationInput? = nil + ) async throws -> [M] { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<[M], Error>) in query(modelType, modelSchema: modelSchema, where: predicate, sort: sortInput, paginate: paginationInput) { result in continuation.resume(with: result) @@ -227,18 +269,22 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { // MARK: - Delete @available(*, deprecated, renamed: "delete(withIdentifier:)") - public func delete(_ modelType: M.Type, - withId id: String, - where predicate: QueryPredicate?) async throws { + public func delete( + _ modelType: M.Type, + withId id: String, + where predicate: QueryPredicate? + ) async throws { try await delete(modelType, modelSchema: modelType.schema, withId: id, where: predicate) } @available(*, deprecated, renamed: "delete(withIdentifier:)") - public func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: String, - where predicate: QueryPredicate? = nil) async throws { + public func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: String, + where predicate: QueryPredicate? = nil + ) async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in switch initStorageEngineAndTryStartSync() { case .success(let storageEngineBehavior): @@ -253,53 +299,71 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func delete(_ modelType: M.Type, - withIdentifier identifier: String, - where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) where M: ModelIdentifiable, + public func delete( + _ modelType: M.Type, + withIdentifier identifier: String, + where predicate: QueryPredicate? = nil, + completion: @escaping DataStoreCallback + ) where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { - deleteByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: DefaultModelIdentifier.makeDefault(id: identifier), - where: predicate, - completion: completion) + deleteByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: DefaultModelIdentifier.makeDefault(id: identifier), + where: predicate, + completion: completion + ) } - public func delete(_ modelType: M.Type, - withIdentifier identifier: String, - where predicate: QueryPredicate? = nil) async throws + public func delete( + _ modelType: M.Type, + withIdentifier identifier: String, + where predicate: QueryPredicate? = nil + ) async throws where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { - try await deleteByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: DefaultModelIdentifier.makeDefault(id: identifier), - where: predicate) - } - - public func delete(_ modelType: M.Type, - withIdentifier identifier: ModelIdentifier, - where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) where M: ModelIdentifiable { - deleteByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: identifier, - where: predicate, - completion: completion) - } - - public func delete(_ modelType: M.Type, - withIdentifier identifier: ModelIdentifier, - where predicate: QueryPredicate? = nil) async throws where M: ModelIdentifiable { - try await deleteByIdentifier(modelType, - modelSchema: modelType.schema, - identifier: identifier, - where: predicate) - } - - private func deleteByIdentifier(_ modelType: M.Type, - modelSchema: ModelSchema, - identifier: ModelIdentifierProtocol, - where predicate: QueryPredicate?, - completion: @escaping DataStoreCallback) where M: ModelIdentifiable { + try await deleteByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: DefaultModelIdentifier.makeDefault(id: identifier), + where: predicate + ) + } + + public func delete( + _ modelType: M.Type, + withIdentifier identifier: ModelIdentifier, + where predicate: QueryPredicate? = nil, + completion: @escaping DataStoreCallback + ) where M: ModelIdentifiable { + deleteByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: identifier, + where: predicate, + completion: completion + ) + } + + public func delete( + _ modelType: M.Type, + withIdentifier identifier: ModelIdentifier, + where predicate: QueryPredicate? = nil + ) async throws where M: ModelIdentifiable { + try await deleteByIdentifier( + modelType, + modelSchema: modelType.schema, + identifier: identifier, + where: predicate + ) + } + + private func deleteByIdentifier( + _ modelType: (some Model & ModelIdentifiable).Type, + modelSchema: ModelSchema, + identifier: ModelIdentifierProtocol, + where predicate: QueryPredicate?, + completion: @escaping DataStoreCallback + ) { switch initStorageEngineAndTryStartSync() { case .success(let storageEngineBehavior): storageEngineBehavior.delete( @@ -320,10 +384,12 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } - private func deleteByIdentifier(_ modelType: M.Type, - modelSchema: ModelSchema, - identifier: ModelIdentifierProtocol, - where predicate: QueryPredicate?) async throws where M: ModelIdentifiable { + private func deleteByIdentifier( + _ modelType: (some Model & ModelIdentifiable).Type, + modelSchema: ModelSchema, + identifier: ModelIdentifierProtocol, + where predicate: QueryPredicate? + ) async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in deleteByIdentifier(modelType, modelSchema: modelSchema, identifier: identifier, where: predicate) { result in continuation.resume(with: result) @@ -331,21 +397,27 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func delete(_ model: M, - where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) { + public func delete( + _ model: some Model, + where predicate: QueryPredicate? = nil, + completion: @escaping DataStoreCallback + ) { delete(model, modelSchema: model.schema, where: predicate, completion: completion) } - public func delete(_ model: M, - where predicate: QueryPredicate? = nil) async throws { + public func delete( + _ model: some Model, + where predicate: QueryPredicate? = nil + ) async throws { try await delete(model, modelSchema: model.schema, where: predicate) } - public func delete(_ model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil, - completion: @escaping DataStoreCallback) { + public func delete( + _ model: some Model, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil, + completion: @escaping DataStoreCallback + ) { switch initStorageEngineAndTryStartSync() { case .success(let storageEngineBehavior): storageEngineBehavior.delete( @@ -362,9 +434,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } - public func delete(_ model: M, - modelSchema: ModelSchema, - where predicate: QueryPredicate? = nil) async throws { + public func delete( + _ model: some Model, + modelSchema: ModelSchema, + where predicate: QueryPredicate? = nil + ) async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in delete(model, modelSchema: modelSchema, where: predicate) { result in continuation.resume(with: result) @@ -372,21 +446,27 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func delete(_ modelType: M.Type, - where predicate: QueryPredicate, - completion: @escaping DataStoreCallback) { + public func delete( + _ modelType: (some Model).Type, + where predicate: QueryPredicate, + completion: @escaping DataStoreCallback + ) { delete(modelType, modelSchema: modelType.schema, where: predicate, completion: completion) } - public func delete(_ modelType: M.Type, - where predicate: QueryPredicate) async throws { + public func delete( + _ modelType: (some Model).Type, + where predicate: QueryPredicate + ) async throws { try await delete(modelType, modelSchema: modelType.schema, where: predicate) } - public func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - where predicate: QueryPredicate, - completion: @escaping DataStoreCallback) { + public func delete( + _ modelType: (some Model).Type, + modelSchema: ModelSchema, + where predicate: QueryPredicate, + completion: @escaping DataStoreCallback + ) { switch initStorageEngineAndTryStartSync() { case .success(let storageEngineBehavior): storageEngineBehavior.delete( @@ -409,9 +489,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - public func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - where predicate: QueryPredicate) async throws { + public func delete( + _ modelType: (some Model).Type, + modelSchema: ModelSchema, + where predicate: QueryPredicate + ) async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in delete(modelType, modelSchema: modelSchema, where: predicate) { result in continuation.resume(with: result) @@ -421,7 +503,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { public func start(completion: @escaping DataStoreCallback) { let result = initStorageEngineAndStartSync().map { _ in () } - self.queue.async { + queue.async { completion(result) } } @@ -437,7 +519,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { public func stop(completion: @escaping DataStoreCallback) { storageEngineInitQueue.sync { self.dataStoreStateSubject.send(.stop) - dispatchedModelSyncedEvents.forEach { _, dispatchedModelSynced in + for (_, dispatchedModelSynced) in dispatchedModelSyncedEvents { dispatchedModelSynced.set(false) } if storageEngine == nil { @@ -471,7 +553,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { storageEngineInitQueue.sync { self.dataStoreStateSubject.send(.clear) - dispatchedModelSyncedEvents.forEach { _, dispatchedModelSynced in + for (_, dispatchedModelSynced) in dispatchedModelSyncedEvents { dispatchedModelSynced.set(false) } if storageEngine == nil { @@ -499,9 +581,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { // MARK: Private - private func onDeleteCompletion(result: DataStoreResult, - modelSchema: ModelSchema, - completion: @escaping DataStoreCallback) { + private func onDeleteCompletion( + result: DataStoreResult<(some Model)?>, + modelSchema: ModelSchema, + completion: @escaping DataStoreCallback + ) { switch result { case .success(let modelOptional): if let model = modelOptional { @@ -513,8 +597,8 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - private func mutationTypeOfModel( - _ model: M, + private func mutationTypeOfModel( + _ model: some Model, modelSchema: ModelSchema, storageEngine: StorageEngineBehavior ) -> Result { @@ -523,9 +607,11 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { guard let engine = storageEngine as? StorageEngine else { throw DataStoreError.configuration("Unable to get storage adapter", "") } - modelExists = try engine.storageAdapter.exists(modelSchema, - withIdentifier: model.identifier(schema: modelSchema), - predicate: nil) + modelExists = try engine.storageAdapter.exists( + modelSchema, + withIdentifier: model.identifier(schema: modelSchema), + predicate: nil + ) } catch { if let dataStoreError = error as? DataStoreError { return .failure(dataStoreError) @@ -538,10 +624,12 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { return .success(modelExists ? MutationEvent.MutationType.update : .create) } - private func publishMutationEvent(from model: M, - modelSchema: ModelSchema, - mutationType: MutationEvent.MutationType) { - guard let storageEngine = storageEngine else { + private func publishMutationEvent( + from model: some Model, + modelSchema: ModelSchema, + mutationType: MutationEvent.MutationType + ) { + guard let storageEngine else { log.info( """ StorageEngine is nil; @@ -552,20 +640,26 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } let metadata = MutationSyncMetadata.keys - let metadataId = MutationSyncMetadata.identifier(modelName: modelSchema.name, - modelId: model.identifier(schema: modelSchema).stringValue) - storageEngine.query(MutationSyncMetadata.self, - predicate: metadata.id == metadataId, - sort: nil, - paginationInput: .firstResult, - eagerLoad: true) { + let metadataId = MutationSyncMetadata.identifier( + modelName: modelSchema.name, + modelId: model.identifier(schema: modelSchema).stringValue + ) + storageEngine.query( + MutationSyncMetadata.self, + predicate: metadata.id == metadataId, + sort: nil, + paginationInput: .firstResult, + eagerLoad: true + ) { do { let result = try $0.get() let syncMetadata = try result.unique() - let mutationEvent = try MutationEvent(model: model, - modelSchema: modelSchema, - mutationType: mutationType, - version: syncMetadata?.version) + let mutationEvent = try MutationEvent( + model: model, + modelSchema: modelSchema, + mutationType: mutationType, + version: syncMetadata?.version + ) self.dataStorePublisher?.send(input: mutationEvent) } catch { self.log.error(error: error) @@ -576,26 +670,34 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } /// Overrides needed by platforms using a serialized version of models (i.e. Flutter) -extension AWSDataStorePlugin { - public func query(_ modelType: M.Type, - modelSchema: ModelSchema, - byIdentifier identifier: ModelIdentifier, - completion: DataStoreCallback) where M: ModelIdentifiable { - queryByIdentifier(modelType, - modelSchema: modelSchema, - identifier: identifier, - completion: completion) - } - - public func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifier, - where predicate: QueryPredicate?, - completion: @escaping DataStoreCallback) where M: ModelIdentifiable { - deleteByIdentifier(modelType, - modelSchema: modelSchema, - identifier: identifier, - where: predicate, - completion: completion) +public extension AWSDataStorePlugin { + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + byIdentifier identifier: ModelIdentifier, + completion: DataStoreCallback + ) where M: ModelIdentifiable { + queryByIdentifier( + modelType, + modelSchema: modelSchema, + identifier: identifier, + completion: completion + ) + } + + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifier, + where predicate: QueryPredicate?, + completion: @escaping DataStoreCallback + ) where M: ModelIdentifiable { + deleteByIdentifier( + modelType, + modelSchema: modelSchema, + identifier: identifier, + where: predicate, + completion: completion + ) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift index ca41efd230..f66d70c35b 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift @@ -21,34 +21,38 @@ extension AWSDataStorePlugin: DataStoreSubscribeBehavior { return publisher.filter { $0.modelName == modelName }.eraseToAnyPublisher() } - public func observe(_ modelType: M.Type) -> AmplifyAsyncThrowingSequence { + public func observe(_ modelType: (some Model).Type) -> AmplifyAsyncThrowingSequence { let runner = ObserveTaskRunner(publisher: publisher(for: modelType.modelName)) return runner.sequence } - public func observeQuery(for modelType: M.Type, - where predicate: QueryPredicate?, - sort sortInput: QuerySortInput?) -> AmplifyAsyncThrowingSequence> { + public func observeQuery( + for modelType: M.Type, + where predicate: QueryPredicate?, + sort sortInput: QuerySortInput? + ) -> AmplifyAsyncThrowingSequence> { switch initStorageEngineAndTryStartSync() { case .success(let storageEngineBehavior): let modelSchema = modelType.schema - guard let dataStorePublisher = dataStorePublisher else { + guard let dataStorePublisher else { return Fatal.preconditionFailure("`dataStorePublisher` is expected to exist for deployment targets >=iOS13.0") } guard let dispatchedModelSyncedEvent = dispatchedModelSyncedEvents[modelSchema.name] else { return Fatal.preconditionFailure("`dispatchedModelSyncedEvent` is expected to exist for \(modelSchema.name)") } let request = ObserveQueryRequest(options: []) - let taskRunner = ObserveQueryTaskRunner(request: request, - modelType: modelType, - modelSchema: modelType.schema, - predicate: predicate, - sortInput: sortInput?.asSortDescriptors(), - storageEngine: storageEngineBehavior, - dataStorePublisher: dataStorePublisher, - dataStoreConfiguration: configuration.pluginConfiguration, - dispatchedModelSyncedEvent: dispatchedModelSyncedEvent, - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + let taskRunner = ObserveQueryTaskRunner( + request: request, + modelType: modelType, + modelSchema: modelType.schema, + predicate: predicate, + sortInput: sortInput?.asSortDescriptors(), + storageEngine: storageEngineBehavior, + dataStorePublisher: dataStorePublisher, + dataStoreConfiguration: configuration.pluginConfiguration, + dispatchedModelSyncedEvent: dispatchedModelSyncedEvent, + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) return taskRunner.sequence case .failure(let error): return Fatal.preconditionFailure("Unable to get storage adapter \(error.localizedDescription)") diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift index cdcbbc2bfb..272a6ac607 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift @@ -6,8 +6,8 @@ // import Amplify -import Combine import AWSPluginsCore +import Combine import Foundation enum DataStoreState { @@ -16,7 +16,7 @@ enum DataStoreState { case clear } -final public class AWSDataStorePlugin: DataStoreCategoryPlugin { +public final class AWSDataStorePlugin: DataStoreCategoryPlugin { public var key: PluginKey = "awsDataStorePlugin" @@ -60,14 +60,17 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { /// - Parameters: /// - modelRegistration: Register DataStore models. /// - dataStoreConfiguration: Configuration object for DataStore - public init(modelRegistration: AmplifyModelRegistration, - configuration dataStoreConfiguration: DataStoreConfiguration) { + public init( + modelRegistration: AmplifyModelRegistration, + configuration dataStoreConfiguration: DataStoreConfiguration + ) { self.modelRegistration = modelRegistration self.configuration = InternalDatastoreConfiguration( isSyncEnabled: false, validAPIPluginKey: "awsAPIPlugin", validAuthPluginKey: "awsCognitoAuthPlugin", - pluginConfiguration: dataStoreConfiguration) + pluginConfiguration: dataStoreConfiguration + ) self.storageEngineBehaviorFactory = StorageEngine.init( @@ -86,14 +89,17 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { /// - Parameters: /// - modelRegistration: Register DataStore models. /// - dataStoreConfiguration: Configuration object for DataStore - public init(modelRegistration: AmplifyModelRegistration, - configuration dataStoreConfiguration: DataStoreConfiguration = .default) { + public init( + modelRegistration: AmplifyModelRegistration, + configuration dataStoreConfiguration: DataStoreConfiguration = .default + ) { self.modelRegistration = modelRegistration self.configuration = InternalDatastoreConfiguration( isSyncEnabled: false, validAPIPluginKey: "awsAPIPlugin", validAuthPluginKey: "awsCognitoAuthPlugin", - pluginConfiguration: dataStoreConfiguration) + pluginConfiguration: dataStoreConfiguration + ) self.storageEngineBehaviorFactory = StorageEngine.init( @@ -110,19 +116,22 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { #endif /// Internal initializer for testing - init(modelRegistration: AmplifyModelRegistration, - configuration dataStoreConfiguration: DataStoreConfiguration = .testDefault(), - storageEngineBehaviorFactory: StorageEngineBehaviorFactory? = nil, - dataStorePublisher: ModelSubcriptionBehavior, - operationQueue: OperationQueue = OperationQueue(), - validAPIPluginKey: String, - validAuthPluginKey: String) { + init( + modelRegistration: AmplifyModelRegistration, + configuration dataStoreConfiguration: DataStoreConfiguration = .testDefault(), + storageEngineBehaviorFactory: StorageEngineBehaviorFactory? = nil, + dataStorePublisher: ModelSubcriptionBehavior, + operationQueue: OperationQueue = OperationQueue(), + validAPIPluginKey: String, + validAuthPluginKey: String + ) { self.modelRegistration = modelRegistration self.configuration = InternalDatastoreConfiguration( isSyncEnabled: false, validAPIPluginKey: validAPIPluginKey, validAuthPluginKey: validAuthPluginKey, - pluginConfiguration: dataStoreConfiguration) + pluginConfiguration: dataStoreConfiguration + ) self.storageEngineBehaviorFactory = storageEngineBehaviorFactory ?? StorageEngine.init( @@ -161,8 +170,8 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { } do { - if self.dataStorePublisher == nil { - self.dataStorePublisher = DataStorePublisher() + if dataStorePublisher == nil { + dataStorePublisher = DataStorePublisher() } try resolveStorageEngine(dataStoreConfiguration: configuration.pluginConfiguration) try storageEngine.setUp(modelSchemas: ModelRegistry.modelSchemas) @@ -251,7 +260,7 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { } func onReceiveValue(receiveValue: StorageEngineEvent) { - guard let dataStorePublisher = self.dataStorePublisher else { + guard let dataStorePublisher else { log.error("Data store publisher not initalized") return } @@ -264,8 +273,10 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { case .modelSyncedEvent(let modelSyncedEvent): log.verbose("Emitting DataStore event: modelSyncedEvent \(modelSyncedEvent)") dispatchedModelSyncedEvents[modelSyncedEvent.modelName]?.set(true) - let modelSyncedEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.modelSynced, - data: modelSyncedEvent) + let modelSyncedEventPayload = HubPayload( + eventName: HubPayload.EventName.DataStore.modelSynced, + data: modelSyncedEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: modelSyncedEventPayload) case .syncQueriesReadyEvent: log.verbose("[Lifecycle event 4]: syncQueriesReady") @@ -284,7 +295,7 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { if let resettable = storageEngine as? Resettable { log.verbose("Resetting storageEngine") await resettable.reset() - self.log.verbose("Resetting storageEngine: finished") + log.verbose("Resetting storageEngine: finished") } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift index 564918daa2..fcfe84030c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation -extension DataStoreConfiguration { +public extension DataStoreConfiguration { - public static let defaultSyncInterval: TimeInterval = .hours(24) - public static let defaultSyncMaxRecords: UInt = 10_000 - public static let defaultSyncPageSize: UInt = 1_000 + static let defaultSyncInterval: TimeInterval = .hours(24) + static let defaultSyncMaxRecords: UInt = 10_000 + static let defaultSyncPageSize: UInt = 1_000 #if os(watchOS) /// Creates a custom configuration. The only required property is `conflictHandler`. @@ -27,7 +27,7 @@ extension DataStoreConfiguration { /// - authModeStrategy: authorization strategy (.default | multiauth) /// - disableSubscriptions: called before establishing subscriptions. Return true to disable subscriptions. /// - Returns: an instance of `DataStoreConfiguration` with the passed parameters. - public static func custom( + static func custom( errorHandler: @escaping DataStoreErrorHandler = { error in Amplify.Logging.error(error: error) }, @@ -41,14 +41,16 @@ extension DataStoreConfiguration { authModeStrategy: AuthModeStrategyType = .default, disableSubscriptions: @escaping () -> Bool ) -> DataStoreConfiguration { - return DataStoreConfiguration(errorHandler: errorHandler, - conflictHandler: conflictHandler, - syncInterval: syncInterval, - syncMaxRecords: syncMaxRecords, - syncPageSize: syncPageSize, - syncExpressions: syncExpressions, - authModeStrategy: authModeStrategy, - disableSubscriptions: disableSubscriptions) + return DataStoreConfiguration( + errorHandler: errorHandler, + conflictHandler: conflictHandler, + syncInterval: syncInterval, + syncMaxRecords: syncMaxRecords, + syncPageSize: syncPageSize, + syncExpressions: syncExpressions, + authModeStrategy: authModeStrategy, + disableSubscriptions: disableSubscriptions + ) } #else /// Creates a custom configuration. The only required property is `conflictHandler`. @@ -61,7 +63,7 @@ extension DataStoreConfiguration { /// - syncPageSize: the page size of each sync execution /// - authModeStrategy: authorization strategy (.default | multiauth) /// - Returns: an instance of `DataStoreConfiguration` with the passed parameters. - public static func custom( + static func custom( errorHandler: @escaping DataStoreErrorHandler = { error in Amplify.Logging.error(error: error) }, @@ -74,13 +76,15 @@ extension DataStoreConfiguration { syncExpressions: [DataStoreSyncExpression] = [], authModeStrategy: AuthModeStrategyType = .default ) -> DataStoreConfiguration { - return DataStoreConfiguration(errorHandler: errorHandler, - conflictHandler: conflictHandler, - syncInterval: syncInterval, - syncMaxRecords: syncMaxRecords, - syncPageSize: syncPageSize, - syncExpressions: syncExpressions, - authModeStrategy: authModeStrategy) + return DataStoreConfiguration( + errorHandler: errorHandler, + conflictHandler: conflictHandler, + syncInterval: syncInterval, + syncMaxRecords: syncMaxRecords, + syncPageSize: syncPageSize, + syncExpressions: syncExpressions, + authModeStrategy: authModeStrategy + ) } #endif @@ -89,12 +93,12 @@ extension DataStoreConfiguration { /// which work on the watchOS simulator but not on the device. Running DataStore on watchOS with subscriptions /// enabled is only possible during special circumstances such as actively streaming audio. /// See https://github.com/aws-amplify/amplify-swift/pull/3368 for more details. - public static var subscriptionsDisabled: DataStoreConfiguration { + static var subscriptionsDisabled: DataStoreConfiguration { .custom(disableSubscriptions: { true }) } #else /// The default configuration. - public static var `default`: DataStoreConfiguration { + static var `default`: DataStoreConfiguration { .custom() } #endif diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift index a1c3ec8788..b25e1b008b 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSPluginsCore +import Foundation /// Error Handler function typealias public typealias DataStoreErrorHandler = (AmplifyError) -> Void @@ -73,14 +73,16 @@ public struct DataStoreConfiguration { public let disableSubscriptions: () -> Bool #if os(watchOS) - init(errorHandler: @escaping DataStoreErrorHandler, - conflictHandler: @escaping DataStoreConflictHandler, - syncInterval: TimeInterval, - syncMaxRecords: UInt, - syncPageSize: UInt, - syncExpressions: [DataStoreSyncExpression], - authModeStrategy: AuthModeStrategyType = .default, - disableSubscriptions: @escaping () -> Bool) { + init( + errorHandler: @escaping DataStoreErrorHandler, + conflictHandler: @escaping DataStoreConflictHandler, + syncInterval: TimeInterval, + syncMaxRecords: UInt, + syncPageSize: UInt, + syncExpressions: [DataStoreSyncExpression], + authModeStrategy: AuthModeStrategyType = .default, + disableSubscriptions: @escaping () -> Bool + ) { self.errorHandler = errorHandler self.conflictHandler = conflictHandler self.syncInterval = syncInterval @@ -91,13 +93,15 @@ public struct DataStoreConfiguration { self.disableSubscriptions = disableSubscriptions } #else - init(errorHandler: @escaping DataStoreErrorHandler, - conflictHandler: @escaping DataStoreConflictHandler, - syncInterval: TimeInterval, - syncMaxRecords: UInt, - syncPageSize: UInt, - syncExpressions: [DataStoreSyncExpression], - authModeStrategy: AuthModeStrategyType = .default) { + init( + errorHandler: @escaping DataStoreErrorHandler, + conflictHandler: @escaping DataStoreConflictHandler, + syncInterval: TimeInterval, + syncMaxRecords: UInt, + syncPageSize: UInt, + syncExpressions: [DataStoreSyncExpression], + authModeStrategy: AuthModeStrategyType = .default + ) { self.errorHandler = errorHandler self.conflictHandler = conflictHandler self.syncInterval = syncInterval diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift index f70585d5a1..34e3968b45 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct InternalDatastoreConfiguration { @@ -32,7 +32,7 @@ struct InternalDatastoreConfiguration { let pluginConfiguration: DataStoreConfiguration mutating func updateIsSyncEnabled(_ isEnabled: Bool) { - self.isSyncEnabled = isEnabled + isSyncEnabled = isEnabled } mutating func updateIsEagerLoad(modelSchema: ModelSchema) { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift index 9241da72e2..4bc09c8fee 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import Combine +import Foundation public struct DataStoreListDecoder: ModelListDecoder { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift index 59aee21603..699d5dd033 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import Combine +import Foundation /// `DataStoreList` is a DataStore-aware custom `Collection` that is capable of loading /// records from the `DataStore` on-demand. This is especially useful when dealing with @@ -21,8 +21,10 @@ public class DataStoreListProvider: ModelListProvider { var loadedState: ModelListProviderState init(metadata: DataStoreListDecoder.Metadata) { - self.loadedState = .notLoaded(associatedIdentifiers: metadata.dataStoreAssociatedIdentifiers, - associatedFields: metadata.dataStoreAssociatedFields) + self.loadedState = .notLoaded( + associatedIdentifiers: metadata.dataStoreAssociatedIdentifiers, + associatedFields: metadata.dataStoreAssociatedFields + ) } init(_ elements: [Element]) { @@ -47,28 +49,32 @@ public class DataStoreListProvider: ModelListProvider { if associatedIdentifiers.count == 1, let associatedId = associatedIdentifiers.first, let associatedField = associatedFields.first { - self.log.verbose("Loading List of \(Element.schema.name) by \(associatedField) == \(associatedId) ") + log.verbose("Loading List of \(Element.schema.name) by \(associatedField) == \(associatedId) ") predicate = field(associatedField) == associatedId } else { let predicateValues = zip(associatedFields, associatedIdentifiers) var queryPredicates: [QueryPredicateOperation] = [] for (identifierName, identifierValue) in predicateValues { - queryPredicates.append(QueryPredicateOperation(field: identifierName, - operator: .equals(identifierValue))) + queryPredicates.append(QueryPredicateOperation( + field: identifierName, + operator: .equals(identifierValue) + )) } - self.log.verbose("Loading List of \(Element.schema.name) by \(associatedFields) == \(associatedIdentifiers) ") + log.verbose("Loading List of \(Element.schema.name) by \(associatedFields) == \(associatedIdentifiers) ") predicate = QueryPredicateGroup(type: .and, predicates: queryPredicates) } do { let elements = try await Amplify.DataStore.query(Element.self, where: predicate) - self.loadedState = .loaded(elements) + loadedState = .loaded(elements) return elements } catch let error as DataStoreError { self.log.error(error: error) - throw CoreError.listOperation("Failed to Query DataStore.", - "See underlying DataStoreError for more details.", - error) + throw CoreError.listOperation( + "Failed to Query DataStore.", + "See underlying DataStoreError for more details.", + error + ) } catch { throw error @@ -81,17 +87,23 @@ public class DataStoreListProvider: ModelListProvider { } public func getNextPage() async throws -> List { - throw CoreError.clientValidation("There is no next page.", - "Only call `getNextPage()` when `hasNextPage()` is true.", - nil) + throw CoreError.clientValidation( + "There is no next page.", + "Only call `getNextPage()` when `hasNextPage()` is true.", + nil + ) } public func encode(to encoder: Encoder) throws { switch loadedState { - case .notLoaded(let associatedIdentifiers, - let associatedFields): - let metadata = DataStoreListDecoder.Metadata(dataStoreAssociatedIdentifiers: associatedIdentifiers, - dataStoreAssociatedFields: associatedFields) + case .notLoaded( + let associatedIdentifiers, + let associatedFields + ): + let metadata = DataStoreListDecoder.Metadata( + dataStoreAssociatedIdentifiers: associatedIdentifiers, + dataStoreAssociatedFields: associatedFields + ) var container = encoder.singleValueContainer() try container.encode(metadata) case .loaded(let elements): diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift index ea4cd42ac9..92288c3984 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import SQLite import AWSPluginsCore +import Foundation +import SQLite public struct DataStoreModelDecoder: ModelProviderDecoder { @@ -17,8 +17,10 @@ public struct DataStoreModelDecoder: ModelProviderDecoder { let identifiers: [LazyReferenceIdentifier] let source: String - init(identifiers: [LazyReferenceIdentifier], - source: String = ModelProviderRegistry.DecoderSource.dataStore) { + init( + identifiers: [LazyReferenceIdentifier], + source: String = ModelProviderRegistry.DecoderSource.dataStore + ) { self.identifiers = identifiers self.source = source } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift index 64878140f9..d80236a773 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import Combine +import Foundation public class DataStoreModelProvider: ModelProvider { var loadedState: ModelProviderState @@ -27,20 +27,20 @@ public class DataStoreModelProvider: ModelProvider { public func load() async throws -> ModelType? { switch loadedState { case .notLoaded(let identifiers): - guard let identifiers = identifiers, !identifiers.isEmpty else { + guard let identifiers, !identifiers.isEmpty else { return nil } let identifierValue = identifiers.count == 1 ? identifiers.first?.value - : identifiers.map({ "\"\($0.value)\""}).joined(separator: ModelIdentifierFormat.Custom.separator) + : identifiers.map { "\"\($0.value)\""}.joined(separator: ModelIdentifierFormat.Custom.separator) let queryPredicate: QueryPredicate = field(ModelType.schema.primaryKey.sqlName).eq(identifierValue) let models = try await Amplify.DataStore.query(ModelType.self, where: queryPredicate) guard let model = models.first else { return nil } - self.loadedState = .loaded(model: model) + loadedState = .loaded(model: model) return model case .loaded(let model): return model diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/DataStoreSyncExpression.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/DataStoreSyncExpression.swift index f1ae361e7b..64f3782f32 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/DataStoreSyncExpression.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/DataStoreSyncExpression.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public typealias QueryPredicateResolver = () -> QueryPredicate @@ -14,8 +14,10 @@ public struct DataStoreSyncExpression { let modelSchema: ModelSchema let modelPredicate: QueryPredicateResolver - static public func syncExpression(_ modelSchema: ModelSchema, - where predicate: @escaping QueryPredicateResolver) -> DataStoreSyncExpression { + public static func syncExpression( + _ modelSchema: ModelSchema, + where predicate: @escaping QueryPredicateResolver + ) -> DataStoreSyncExpression { DataStoreSyncExpression(modelSchema: modelSchema, modelPredicate: predicate) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift index 0a0eb72e03..dc73d7039b 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore class ModelSyncMetadataMigration: ModelMigration { @@ -37,19 +37,22 @@ class ModelSyncMetadataMigration: ModelMigration { func performModelMetadataSyncPredicateUpgrade() throws -> Bool { do { guard let field = ModelSyncMetadata.schema.field( - withName: ModelSyncMetadata.keys.syncPredicate.stringValue) else { + withName: ModelSyncMetadata.keys.syncPredicate.stringValue) + else { log.error("Could not find corresponding ModelField from ModelSyncMetadata for syncPredicate") return false } - let exists = try columnExists(modelSchema: ModelSyncMetadata.schema, - field: field) + let exists = try columnExists( + modelSchema: ModelSyncMetadata.schema, + field: field + ) guard !exists else { log.debug("Detected ModelSyncMetadata table has syncPredicate column. No migration needed") return false } log.debug("Detected ModelSyncMetadata table exists without syncPredicate column.") - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -58,7 +61,8 @@ class ModelSyncMetadataMigration: ModelMigration { } let addColumnStatement = AlterTableAddColumnStatement( modelSchema: ModelSyncMetadata.schema, - field: field).stringValue + field: field + ).stringValue try connection.execute(addColumnStatement) log.debug("ModelSyncMetadata table altered to add syncPredicate column.") return true @@ -68,7 +72,7 @@ class ModelSyncMetadataMigration: ModelMigration { } func columnExists(modelSchema: ModelSchema, field: ModelField) throws -> Bool { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataCopy.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataCopy.swift index 855b3cf079..32eb5a7bad 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataCopy.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataCopy.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension MutationSyncMetadataMigration { - public struct MutationSyncMetadataCopy: Model { + struct MutationSyncMetadataCopy: Model { public let id: String public var deleted: Bool public var lastChangedAt: Int64 diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigration.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigration.swift index f32c027cad..02fba91670 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigration.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigration.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSPluginsCore +import Foundation /// Migrates `MutationSyncMetadata` to the new format. /// @@ -23,7 +23,7 @@ class MutationSyncMetadataMigration: ModelMigration { } func apply() throws { - guard let delegate = delegate else { + guard let delegate else { log.debug("Missing MutationSyncMetadataMigrationDelegate delegate") throw DataStoreError.unknown("Missing MutationSyncMetadataMigrationDelegate delegate", "", nil) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLite.swift index 29aad4f815..fa2b198746 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLite.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMigrationDelegate { @@ -46,7 +46,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig // MARK: - Clear @discardableResult func emptyMutationSyncMetadataStore() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -55,7 +55,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig } @discardableResult func emptyModelSyncMetadataStore() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -66,7 +66,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig // MARK: - Migration @discardableResult func removeMutationSyncMetadataCopyStore() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -75,7 +75,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig } @discardableResult func createMutationSyncMetadataCopyStore() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -84,7 +84,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig } @discardableResult func backfillMutationSyncMetadata() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -110,7 +110,7 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig } @discardableResult func removeMutationSyncMetadataStore() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -119,13 +119,15 @@ final class SQLiteMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMig } @discardableResult func renameMutationSyncMetadataCopy() throws -> String { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } - return try storageAdapter.renameStore(from: MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema, - toModelSchema: MutationSyncMetadata.schema) + return try storageAdapter.renameStore( + from: MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema, + toModelSchema: MutationSyncMetadata.schema + ) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLiteValidation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLiteValidation.swift index 33115bf373..16122b8bdb 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLiteValidation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/MutationSyncMetadataMigrationDelegate+SQLiteValidation.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore extension SQLiteMutationSyncMetadataMigrationDelegate { @@ -30,7 +30,8 @@ extension SQLiteMutationSyncMetadataMigrationDelegate { guard MutationSyncMetadata.schema.fields[idField] != nil, MutationSyncMetadata.schema.fields[deletedField] != nil, MutationSyncMetadata.schema.fields[lastChangedAtField] != nil, - MutationSyncMetadata.schema.fields[versionField] != nil else { + MutationSyncMetadata.schema.fields[versionField] != nil + else { throw DataStoreError.internalOperation("MutationSyncMetadata schema missing expected fields", "", nil) } @@ -41,7 +42,8 @@ extension SQLiteMutationSyncMetadataMigrationDelegate { guard MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema.fields[idField] != nil, MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema.fields[deletedField] != nil, MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema.fields[lastChangedAtField] != nil, - MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema.fields[versionField] != nil else { + MutationSyncMetadataMigration.MutationSyncMetadataCopy.schema.fields[versionField] != nil + else { throw DataStoreError.internalOperation("MutationSyncMetadataCopy schema missing expected fields", "", nil) } } @@ -64,7 +66,7 @@ extension SQLiteMutationSyncMetadataMigrationDelegate { /// 1. the total number of records /// 2. the total number of records that have the `id` match `|` func selectMutationSyncMetadataRecords() throws -> (metadataCount: Int64, metadataIdMatchNewKeyCount: Int64) { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } @@ -93,7 +95,7 @@ extension SQLiteMutationSyncMetadataMigrationDelegate { // MARK: - Cannot Migrate func containsDuplicateIdsAcrossModels() throws -> Bool { - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") throw DataStoreError.nilStorageAdapter() } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift index 29687e390c..c90b03db15 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore import Combine +import Foundation // swiftlint:disable type_body_length file_length /// CascadeDeleteOperation has the following logic: @@ -40,10 +40,11 @@ public class CascadeDeleteOperation: AsynchronousOperation { modelSchema: ModelSchema, withIdentifier identifier: ModelIdentifierProtocol, condition: QueryPredicate? = nil, - completion: @escaping (DataStoreResult) -> Void) { + completion: @escaping (DataStoreResult) -> Void + ) { var deleteInput = DeleteInput.withIdentifier(id: identifier) - if let condition = condition { + if let condition { deleteInput = .withIdentifierAndCondition(id: identifier, condition: condition) } self.init( @@ -53,7 +54,8 @@ public class CascadeDeleteOperation: AsynchronousOperation { modelSchema: modelSchema, deleteInput: deleteInput, completionForWithId: completion, - completionForWithFilter: nil) + completionForWithFilter: nil + ) } convenience init( @@ -62,7 +64,8 @@ public class CascadeDeleteOperation: AsynchronousOperation { modelType: M.Type, modelSchema: ModelSchema, filter: QueryPredicate, - completion: @escaping (DataStoreResult<[M]>) -> Void) { + completion: @escaping (DataStoreResult<[M]>) -> Void + ) { self.init( storageAdapter: storageAdapter, syncEngine: syncEngine, @@ -74,13 +77,14 @@ public class CascadeDeleteOperation: AsynchronousOperation { ) } - private init(storageAdapter: StorageEngineAdapter, - syncEngine: RemoteSyncEngineBehavior?, - modelType: M.Type, - modelSchema: ModelSchema, - deleteInput: DeleteInput, - completionForWithId: ((DataStoreResult) -> Void)?, - completionForWithFilter: ((DataStoreResult<[M]>) -> Void)? + private init( + storageAdapter: StorageEngineAdapter, + syncEngine: RemoteSyncEngineBehavior?, + modelType: M.Type, + modelSchema: ModelSchema, + deleteInput: DeleteInput, + completionForWithId: ((DataStoreResult) -> Void)?, + completionForWithFilter: ((DataStoreResult<[M]>) -> Void)? ) { self.storageAdapter = storageAdapter self.syncEngine = syncEngine @@ -118,36 +122,43 @@ public class CascadeDeleteOperation: AsynchronousOperation { var associatedModels: [(ModelName, Model)] = [] queriedResult = await withCheckedContinuation { continuation in - self.storageAdapter.query(self.modelType, - modelSchema: self.modelSchema, - predicate: self.deleteInput.predicate, - sort: nil, - paginationInput: nil, - eagerLoad: true) { result in + self.storageAdapter.query( + self.modelType, + modelSchema: self.modelSchema, + predicate: self.deleteInput.predicate, + sort: nil, + paginationInput: nil, + eagerLoad: true + ) { result in continuation.resume(returning: result) } } guard case .success(let queriedModels) = queriedResult else { - return collapseResults(queryResult: queriedResult, - deleteResult: deletedResult, - associatedModels: associatedModels) + return collapseResults( + queryResult: queriedResult, + deleteResult: deletedResult, + associatedModels: associatedModels + ) } guard !queriedModels.isEmpty else { - guard case .withIdentifierAndCondition(let identifier, _) = self.deleteInput else { + guard case .withIdentifierAndCondition(let identifier, _) = deleteInput else { // Query did not return any results, treat this as a successful no-op delete. deletedResult = .success([M]()) - return collapseResults(queryResult: queriedResult, - deleteResult: deletedResult, - associatedModels: associatedModels) + return collapseResults( + queryResult: queriedResult, + deleteResult: deletedResult, + associatedModels: associatedModels + ) } // Query using the computed predicate did not return any results, check if model actually exists. do { - if try self.storageAdapter.exists(self.modelSchema, withIdentifier: identifier, predicate: nil) { + if try storageAdapter.exists(modelSchema, withIdentifier: identifier, predicate: nil) { queriedResult = .failure( DataStoreError.invalidCondition( "Delete failed due to condition did not match existing model instance.", - "Subsequent deletes will continue to fail until the model instance is updated.")) + "Subsequent deletes will continue to fail until the model instance is updated." + )) } else { deletedResult = .success([M]()) } @@ -155,26 +166,33 @@ public class CascadeDeleteOperation: AsynchronousOperation { queriedResult = .failure(DataStoreError.invalidOperation(causedBy: error)) } - return collapseResults(queryResult: queriedResult, - deleteResult: deletedResult, - associatedModels: associatedModels) + return collapseResults( + queryResult: queriedResult, + deleteResult: deletedResult, + associatedModels: associatedModels + ) } let modelIds = queriedModels.map { $0.identifier(schema: self.modelSchema).stringValue } + // swiftformat:disable redundantSelf logMessage("[CascadeDelete.1] Deleting \(self.modelSchema.name) with identifiers: \(modelIds)") - - associatedModels = await self.recurseQueryAssociatedModels(modelSchema: self.modelSchema, ids: modelIds) + // swiftformat:enable redundantSelf + associatedModels = await recurseQueryAssociatedModels(modelSchema: modelSchema, ids: modelIds) deletedResult = await withCheckedContinuation { continuation in - self.storageAdapter.delete(self.modelType, - modelSchema: self.modelSchema, - filter: self.deleteInput.predicate) { result in + self.storageAdapter.delete( + self.modelType, + modelSchema: self.modelSchema, + filter: self.deleteInput.predicate + ) { result in continuation.resume(returning: result) } } - return collapseResults(queryResult: queriedResult, - deleteResult: deletedResult, - associatedModels: associatedModels) + return collapseResults( + queryResult: queriedResult, + deleteResult: deletedResult, + associatedModels: associatedModels + ) } func recurseQueryAssociatedModels(modelSchema: ModelSchema, ids: [String]) async -> [(ModelName, Model)] { @@ -195,7 +213,8 @@ public class CascadeDeleteOperation: AsynchronousOperation { let queriedModels = await queryAssociatedModels( associatedModelSchema: associatedModelSchema, associatedField: associatedField, - ids: ids) + ids: ids + ) let associatedModelIds = queriedModels.map { $0.1.identifier(schema: associatedModelSchema).stringValue @@ -204,18 +223,21 @@ public class CascadeDeleteOperation: AsynchronousOperation { logMessage("[CascadeDelete.2] Queried for \(associatedModelSchema.name), retrieved ids for deletion: \(associatedModelIds)") associatedModels.append(contentsOf: queriedModels) - associatedModels.append(contentsOf: await recurseQueryAssociatedModels( + await associatedModels.append(contentsOf: recurseQueryAssociatedModels( modelSchema: associatedModelSchema, - ids: associatedModelIds) + ids: associatedModelIds + ) ) } return associatedModels } - func queryAssociatedModels(associatedModelSchema modelSchema: ModelSchema, - associatedField: ModelField, - ids: [String]) async -> [(ModelName, Model)] { + func queryAssociatedModels( + associatedModelSchema modelSchema: ModelSchema, + associatedField: ModelField, + ids: [String] + ) async -> [(ModelName, Model)] { var queriedModels: [(ModelName, Model)] = [] let chunkedArrays = ids.chunked(into: SQLiteStorageEngineAdapter.maxNumberOfPredicates) for chunkedArray in chunkedArrays { @@ -248,21 +270,25 @@ public class CascadeDeleteOperation: AsynchronousOperation { associatedModels: [(ModelName, Model)] ) -> DataStoreResult> { - guard let queryResult = queryResult else { + guard let queryResult else { return .failure(.unknown("queryResult not set during transaction", "coding error", nil)) } switch queryResult { case .success(let models): - guard let deleteResult = deleteResult else { + guard let deleteResult else { return .failure(.unknown("deleteResult not set during transaction", "coding error", nil)) } switch deleteResult { case .success: + // swiftformat:disable redundantSelf logMessage("[CascadeDelete.3] Local cascade delete of \(self.modelSchema.name) successful!") - return .success(QueryAndDeleteResult(deletedModels: models, - associatedModels: associatedModels)) + // swiftformat:enable redundantSelf + return .success(QueryAndDeleteResult( + deletedModels: models, + associatedModels: associatedModels + )) case .failure(let error): return .failure(error) } @@ -302,7 +328,7 @@ public class CascadeDeleteOperation: AsynchronousOperation { } } - guard modelSchema.isSyncable, let syncEngine = self.syncEngine else { + guard modelSchema.isSyncable, let syncEngine else { if !modelSchema.isSystem { log.error("Unable to sync model (\(modelSchema.name)) where isSyncable is false") } @@ -336,9 +362,11 @@ public class CascadeDeleteOperation: AsynchronousOperation { // mutation? switch deleteInput { case .withIdentifier, .withIdentifierAndCondition: - syncDeletions(withModels: queryAndDeleteResult.deletedModels, - associatedModels: queryAndDeleteResult.associatedModels, - syncEngine: syncEngine) { + syncDeletions( + withModels: queryAndDeleteResult.deletedModels, + associatedModels: queryAndDeleteResult.associatedModels, + syncEngine: syncEngine + ) { switch $0 { case .success: self.completionForWithId?(.success(queryAndDeleteResult.deletedModels.first)) @@ -348,10 +376,12 @@ public class CascadeDeleteOperation: AsynchronousOperation { self.finish() } case .withFilter(let filter): - syncDeletions(withModels: queryAndDeleteResult.deletedModels, - predicate: filter, - associatedModels: queryAndDeleteResult.associatedModels, - syncEngine: syncEngine) { + syncDeletions( + withModels: queryAndDeleteResult.deletedModels, + predicate: filter, + associatedModels: queryAndDeleteResult.associatedModels, + syncEngine: syncEngine + ) { switch $0 { case .success: self.completionForWithFilter?(.success(queryAndDeleteResult.deletedModels)) @@ -382,30 +412,36 @@ public class CascadeDeleteOperation: AsynchronousOperation { // collection and provide access in reverse order. // For more details: https://developer.apple.com/documentation/swift/array/1690025-reversed @available(iOS 13.0, *) - private func syncDeletions(withModels models: [M], - predicate: QueryPredicate? = nil, - associatedModels: [(ModelName, Model)], - syncEngine: RemoteSyncEngineBehavior, - completion: @escaping DataStoreCallback) { + private func syncDeletions( + withModels models: [M], + predicate: QueryPredicate? = nil, + associatedModels: [(ModelName, Model)], + syncEngine: RemoteSyncEngineBehavior, + completion: @escaping DataStoreCallback + ) { var savedDataStoreError: DataStoreError? guard !associatedModels.isEmpty else { - syncDeletions(withModels: models, - predicate: predicate, - syncEngine: syncEngine, - dataStoreError: savedDataStoreError, - completion: completion) + syncDeletions( + withModels: models, + predicate: predicate, + syncEngine: syncEngine, + dataStoreError: savedDataStoreError, + completion: completion + ) return } - self.log.debug("[CascadeDelete.4] Begin syncing \(associatedModels.count) associated models for deletion. ") + log.debug("[CascadeDelete.4] Begin syncing \(associatedModels.count) associated models for deletion. ") var mutationEventsSubmitCompleted = 0 for (modelName, associatedModel) in associatedModels.reversed() { let mutationEvent: MutationEvent do { - mutationEvent = try MutationEvent(untypedModel: associatedModel, - modelName: modelName, - mutationType: .delete) + mutationEvent = try MutationEvent( + untypedModel: associatedModel, + modelName: modelName, + mutationType: .delete + ) } catch { let dataStoreError = DataStoreError(error: error) completion(.failure(dataStoreError)) @@ -426,33 +462,43 @@ public class CascadeDeleteOperation: AsynchronousOperation { } if mutationEventsSubmitCompleted == associatedModels.count { - self.syncDeletions(withModels: models, - predicate: predicate, - syncEngine: syncEngine, - dataStoreError: savedDataStoreError, - completion: completion) + self.syncDeletions( + withModels: models, + predicate: predicate, + syncEngine: syncEngine, + dataStoreError: savedDataStoreError, + completion: completion + ) } } } - submitToSyncEngine(mutationEvent: mutationEvent, - syncEngine: syncEngine, - completion: mutationEventCallback) + submitToSyncEngine( + mutationEvent: mutationEvent, + syncEngine: syncEngine, + completion: mutationEventCallback + ) } } @available(iOS 13.0, *) - private func syncDeletions(withModels models: [M], - predicate: QueryPredicate? = nil, - syncEngine: RemoteSyncEngineBehavior, - dataStoreError: DataStoreError?, - completion: @escaping DataStoreCallback) { + private func syncDeletions( + withModels models: [M], + predicate: QueryPredicate? = nil, + syncEngine: RemoteSyncEngineBehavior, + dataStoreError: DataStoreError?, + completion: @escaping DataStoreCallback + ) { + // swiftformat:disable redundantSelf logMessage("[CascadeDelete.4] Begin syncing \(models.count) \(self.modelSchema.name) model for deletion") + // swiftformat:enable redundantSelf var graphQLFilterJSON: String? - if let predicate = predicate { + if let predicate { do { - graphQLFilterJSON = try GraphQLFilterConverter.toJSON(predicate, - modelSchema: modelSchema) + graphQLFilterJSON = try GraphQLFilterConverter.toJSON( + predicate, + modelSchema: modelSchema + ) } catch { let dataStoreError = DataStoreError(error: error) completion(.failure(dataStoreError)) @@ -464,10 +510,12 @@ public class CascadeDeleteOperation: AsynchronousOperation { for model in models { let mutationEvent: MutationEvent do { - mutationEvent = try MutationEvent(model: model, - modelSchema: modelSchema, - mutationType: .delete, - graphQLFilterJSON: graphQLFilterJSON) + mutationEvent = try MutationEvent( + model: model, + modelSchema: modelSchema, + mutationType: .delete, + graphQLFilterJSON: graphQLFilterJSON + ) } catch { let dataStoreError = DataStoreError(error: error) completion(.failure(dataStoreError)) @@ -496,21 +544,26 @@ public class CascadeDeleteOperation: AsynchronousOperation { } } - submitToSyncEngine(mutationEvent: mutationEvent, - syncEngine: syncEngine, - completion: mutationEventCallback) + submitToSyncEngine( + mutationEvent: mutationEvent, + syncEngine: syncEngine, + completion: mutationEventCallback + ) } } - private func submitToSyncEngine(mutationEvent: MutationEvent, - syncEngine: RemoteSyncEngineBehavior, - completion: @escaping DataStoreCallback) { + private func submitToSyncEngine( + mutationEvent: MutationEvent, + syncEngine: RemoteSyncEngineBehavior, + completion: @escaping DataStoreCallback + ) { syncEngine.submit(mutationEvent, completion: completion) } private func logMessage( _ message: @escaping @autoclosure () -> String, - level log: (() -> String) -> Void = log.debug) { + level log: (() -> String) -> Void = log.debug + ) { guard isDeveloperDefinedModel else { return } log(message) } @@ -535,9 +588,13 @@ extension CascadeDeleteOperation { case .withIdentifier(let identifier): return identifier.predicate case .withIdentifierAndCondition(let identifier, let predicate): - return QueryPredicateGroup(type: .and, - predicates: [identifier.predicate, - predicate]) + return QueryPredicateGroup( + type: .and, + predicates: [ + identifier.predicate, + predicate + ] + ) case .withFilter(let predicate): return predicate } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift index e33537baa5..b4dca1abc4 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift @@ -15,49 +15,63 @@ protocol ModelStorageBehavior { /// Apply any data migration logic for the given schemas in the underlying data store. func applyModelMigrations(modelSchemas: [ModelSchema]) throws - func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) + func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) - func save(_ model: M, - condition: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) + func save( + _ model: M, + condition: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) @available(*, deprecated, message: "Use delete(:modelSchema:withIdentifier:predicate:completion") - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: Model.Identifier, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: Model.Identifier, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) - func query(_ modelType: M.Type, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: DataStoreCallback<[M]>) + func query( + _ modelType: M.Type, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: DataStoreCallback<[M]> + ) - func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: DataStoreCallback<[M]>) + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: DataStoreCallback<[M]> + ) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift index 7ff35dccb2..1570a7030d 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore /// Extended types that conform to `Persistable` in order to provide conversion to SQLite's `Binding` /// types. This is necessary so `Model` properties' map values to a SQLite compatible types. @@ -22,12 +22,14 @@ extension Persistable { /// - Note: a `preconditionFailure` might happen in case the value cannot be converted. /// /// - Returns: the value as `Binding` - internal func asBinding() -> Binding { + func asBinding() -> Binding { let value = self let valueType = type(of: value) do { - let binding = try SQLiteModelValueConverter.convertToTarget(from: value, - fieldType: .from(type: valueType)) + let binding = try SQLiteModelValueConverter.convertToTarget( + from: value, + fieldType: .from(type: valueType) + ) guard let validBinding = binding else { return Fatal.preconditionFailure(""" Converting \(String(describing: value)) of type \(String(describing: valueType)) @@ -58,7 +60,7 @@ extension Model { /// /// - Parameter fields: an optional subset of fields /// - Returns: an array of SQLite's `Binding` compatible type - internal func sqlValues(for fields: [ModelField]? = nil, modelSchema: ModelSchema) -> [Binding?] { + func sqlValues(for fields: [ModelField]? = nil, modelSchema: ModelSchema) -> [Binding?] { let modelFields = fields ?? modelSchema.sortedFields let values: [Binding?] = modelFields.map { field in @@ -117,7 +119,7 @@ extension Model { // from the not loaded identifier's stringValue (the value, or the formatted value for CPK) switch associatedLazyModel._state { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { return nil } return identifiers.stringValue @@ -125,8 +127,10 @@ extension Model { return model?.identifier } } else if let associatedModelJSON = value as? [String: JSONValue] { - return associatedPrimaryKeyValue(fromJSON: associatedModelJSON, - associatedModelSchema: associatedModelSchema) + return associatedPrimaryKeyValue( + fromJSON: associatedModelJSON, + associatedModelSchema: associatedModelSchema + ) } } @@ -153,8 +157,10 @@ extension Model { /// - associatedModelJSON: model as JSON value /// - associatedModelSchema: model's schema /// - Returns: serialized value of the primary key - private func associatedPrimaryKeyValue(fromJSON associatedModelJSON: [String: JSONValue], - associatedModelSchema: ModelSchema) -> String { + private func associatedPrimaryKeyValue( + fromJSON associatedModelJSON: [String: JSONValue], + associatedModelSchema: ModelSchema + ) -> String { let associatedModelPKFields: ModelIdentifierProtocol.Fields // get the associated model primary key fields @@ -172,7 +178,7 @@ extension Model { } -extension Array where Element == ModelSchema { +extension [ModelSchema] { /// Sort the [ModelSchema] array based on the associations between them. /// @@ -200,7 +206,7 @@ extension Array where Element == ModelSchema { if !sortedKeys.contains(schema.name) { let associatedModelSchemas = schema.sortedFields .filter { $0.isForeignKey } - .map { (schema) -> ModelSchema in + .map { schema -> ModelSchema in guard let associatedSchema = ModelRegistry.modelSchema(from: schema.requiredAssociatedModelName) else { return Fatal.preconditionFailure(""" @@ -230,7 +236,7 @@ extension Array where Element == ModelSchema { } } -extension ModelIdentifierFormat.Custom { +public extension ModelIdentifierFormat.Custom { /// Name for composite identifier (multiple fields) - public static let sqlColumnName = "@@primaryKey" + static let sqlColumnName = "@@primaryKey" } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelSchema+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelSchema+SQLite.swift index ab3bf52aff..3fd7a15ae4 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelSchema+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelSchema+SQLite.swift @@ -41,10 +41,12 @@ extension ModelPrimaryKey: SQLColumn { /// Convenience method to convert a ModelPrimaryKey to an /// ModelField to be used in a SQL query var asField: ModelField { - ModelField(name: name, - type: .string, - isRequired: true, - attributes: [.primaryKey]) + ModelField( + name: name, + type: .string, + isRequired: true, + attributes: [.primaryKey] + ) } var sqlType: SQLDataType { @@ -69,7 +71,7 @@ extension ModelPrimaryKey: SQLColumn { } let columnName = ModelIdentifierFormat.Custom.sqlColumnName.quoted() - if let namespace = namespace { + if let namespace { return "\(namespace.quoted()).\(columnName)" } @@ -130,7 +132,7 @@ extension ModelField: SQLColumn { /// - Returns: a valid (i.e. escaped) SQL column name func columnName(forNamespace namespace: String? = nil) -> String { var column = sqlName.quoted() - if let namespace = namespace { + if let namespace { column = namespace.quoted() + "." + column } return column @@ -148,7 +150,7 @@ extension ModelField: SQLColumn { /// the call `field.columnAlias(forNamespace: "post")` would return `as "post.id"`. func columnAlias(forNamespace namespace: String? = nil) -> String { var column = sqlName - if let namespace = namespace { + if let namespace { column = "\(namespace).\(column)" } return column.quoted() @@ -172,14 +174,14 @@ extension ModelSchema { /// Filter the fields that represent foreign keys. var foreignKeys: [ModelField] { - sortedFields.filter { $0.isForeignKey } + sortedFields.filter(\.isForeignKey) } /// Create SQLite indexes corresponding to secondary indexes in the model schema func createIndexStatements() -> String { // Store field names used to represent associations for a fast lookup var associationsFields = Set() - for (_, field) in self.fields { + for (_, field) in fields { if field.isAssociationOwner, let association = field.association, case let .belongsTo(_, targetNames: targetNames) = association { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelValueConverter+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelValueConverter+SQLite.swift index ab1a85aed9..523802f8ce 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelValueConverter+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/ModelValueConverter+SQLite.swift @@ -9,7 +9,7 @@ import Amplify import Foundation import SQLite -internal extension Bool { +extension Bool { var intValue: Int { return self ? Int(1) : Int(0) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/QuerySortDescriptor.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/QuerySortDescriptor.swift index 913e63545a..d3436c6925 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/QuerySortDescriptor.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/QuerySortDescriptor.swift @@ -31,22 +31,26 @@ public enum QuerySortOrder: String { case descending = "desc" } -extension Array where Element == QuerySortDescriptor { +extension [QuerySortDescriptor] { /// Generates the sorting part of the sql statement. /// /// For a sort description of ascending on `Post.createdAt` will return the string `"\"root\".\"createdAt\" asc"` /// where `root` is the namespace. func sortStatement(namespace: String) -> String { - let sqlResult = map { Array.columnFor(field: $0.fieldName, - order: $0.order.rawValue, - namespace: namespace) } + let sqlResult = map { Array.columnFor( + field: $0.fieldName, + order: $0.order.rawValue, + namespace: namespace + ) } return sqlResult.joined(separator: ", ") } - static func columnFor(field: String, - order: String, - namespace: String) -> String { + static func columnFor( + field: String, + order: String, + namespace: String + ) -> String { return namespace.quoted() + "." + field.quoted() + " " + order } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Condition.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Condition.swift index 6d8d55136c..1f6c26128c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Condition.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Condition.swift @@ -18,9 +18,11 @@ typealias SQLPredicate = (String, [Binding?]) /// - modelSchema: the model schema of the `Model` /// - predicate: the query predicate /// - Returns: a tuple containing the SQL string and the associated values -private func translateQueryPredicate(from modelSchema: ModelSchema, - predicate: QueryPredicate, - namespace: Substring? = nil) -> SQLPredicate { +private func translateQueryPredicate( + from modelSchema: ModelSchema, + predicate: QueryPredicate, + namespace: Substring? = nil +) -> SQLPredicate { var sql: [String] = [] var bindings: [Binding?] = [] let indentPrefix = " " @@ -66,11 +68,11 @@ private func translateQueryPredicate(from modelSchema: ModelSchema, func resolveColumn(_ operation: QueryPredicateOperation) -> String { let modelField = modelSchema.field(withName: operation.field) - if let namespace = namespace, let modelField = modelField { + if let namespace, let modelField { return modelField.columnName(forNamespace: String(namespace)) - } else if let modelField = modelField { + } else if let modelField { return modelField.columnName() - } else if let namespace = namespace { + } else if let namespace { return String(namespace).quoted() + "." + operation.field.quoted() } return operation.field.quoted() @@ -93,9 +95,11 @@ struct ConditionStatement: SQLStatement { init(modelSchema: ModelSchema, predicate: QueryPredicate, namespace: Substring? = nil) { self.modelSchema = modelSchema - let (sql, variables) = translateQueryPredicate(from: modelSchema, - predicate: predicate, - namespace: namespace) + let (sql, variables) = translateQueryPredicate( + from: modelSchema, + predicate: predicate, + namespace: namespace + ) self.stringValue = sql self.variables = variables } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Delete.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Delete.swift index 26290d6968..162824d773 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Delete.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Delete.swift @@ -20,31 +20,39 @@ struct DeleteStatement: SQLStatement { self.modelSchema = modelSchema var conditionStatement: ConditionStatement? - if let predicate = predicate { - let statement = ConditionStatement(modelSchema: modelSchema, - predicate: predicate, - namespace: namespace[...]) + if let predicate { + let statement = ConditionStatement( + modelSchema: modelSchema, + predicate: predicate, + namespace: namespace[...] + ) conditionStatement = statement } self.conditionStatement = conditionStatement } - init(_: M.Type, - modelSchema: ModelSchema, - withId id: String, - predicate: QueryPredicate? = nil) { + init( + _: M.Type, + modelSchema: ModelSchema, + withId id: String, + predicate: QueryPredicate? = nil + ) { let identifier = DefaultModelIdentifier.makeDefault(id: id) - self.init(modelSchema: modelSchema, - withIdentifier: identifier, - predicate: predicate) + self.init( + modelSchema: modelSchema, + withIdentifier: identifier, + predicate: predicate + ) } - init(modelSchema: ModelSchema, - withIdentifier id: ModelIdentifierProtocol, - predicate: QueryPredicate? = nil) { + init( + modelSchema: ModelSchema, + withIdentifier id: ModelIdentifierProtocol, + predicate: QueryPredicate? = nil + ) { var queryPredicate: QueryPredicate = field(modelSchema.primaryKey.sqlName) .eq(id.stringValue) - if let predicate = predicate { + if let predicate { queryPredicate = field(modelSchema.primaryKey.sqlName) .eq(id.stringValue).and(predicate) } @@ -60,7 +68,7 @@ struct DeleteStatement: SQLStatement { delete from "\(modelSchema.name)" as \(namespace) """ - if let conditionStatement = conditionStatement { + if let conditionStatement { return """ \(sql) where 1 = 1 diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Select.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Select.swift index 9a0b9e909a..10740385bb 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Select.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Select.swift @@ -19,11 +19,13 @@ struct SelectStatementMetadata { let columnMapping: ColumnMapping let bindings: [Binding?] - static func metadata(from modelSchema: ModelSchema, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true) -> SelectStatementMetadata { + static func metadata( + from modelSchema: ModelSchema, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true + ) -> SelectStatementMetadata { let rootNamespace = "root" let fields = modelSchema.columns let tableName = modelSchema.name @@ -46,10 +48,12 @@ struct SelectStatementMetadata { """.trimmingCharacters(in: .whitespacesAndNewlines) var bindings: [Binding?] = [] - if let predicate = predicate { - let conditionStatement = ConditionStatement(modelSchema: modelSchema, - predicate: predicate, - namespace: rootNamespace[...]) + if let predicate { + let conditionStatement = ConditionStatement( + modelSchema: modelSchema, + predicate: predicate, + namespace: rootNamespace[...] + ) bindings.append(contentsOf: conditionStatement.variables) sql = """ \(sql) @@ -58,23 +62,25 @@ struct SelectStatementMetadata { """ } - if let sort = sort, !sort.isEmpty { + if let sort, !sort.isEmpty { sql = """ \(sql) order by \(sort.sortStatement(namespace: rootNamespace)) """ } - if let paginationInput = paginationInput { + if let paginationInput { sql = """ \(sql) \(paginationInput.sqlStatement) """ } - return SelectStatementMetadata(statement: sql, - columnMapping: columnMapping, - bindings: bindings) + return SelectStatementMetadata( + statement: sql, + columnMapping: columnMapping, + bindings: bindings + ) } struct JoinStatement { @@ -92,9 +98,11 @@ struct SelectStatementMetadata { var joinStatements: [String] = [] var columnMapping: ColumnMapping = [:] guard eagerLoad == true else { - return JoinStatement(columns: columns, - statements: joinStatements, - columnMapping: columnMapping) + return JoinStatement( + columns: columns, + statements: joinStatements, + columnMapping: columnMapping + ) } func visitAssociations(node: ModelSchema, namespace: String = "root") { @@ -131,9 +139,11 @@ struct SelectStatementMetadata { } visitAssociations(node: schema) - return JoinStatement(columns: columns, - statements: joinStatements, - columnMapping: columnMapping) + return JoinStatement( + columns: columns, + statements: joinStatements, + columnMapping: columnMapping + ) } } @@ -145,17 +155,21 @@ struct SelectStatement: SQLStatement { let modelSchema: ModelSchema let metadata: SelectStatementMetadata - init(from modelSchema: ModelSchema, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true) { + init( + from modelSchema: ModelSchema, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true + ) { self.modelSchema = modelSchema - self.metadata = .metadata(from: modelSchema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad) + self.metadata = .metadata( + from: modelSchema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad + ) } var stringValue: String { @@ -175,7 +189,7 @@ struct SelectStatement: SQLStatement { /// - Parameter columns the list of column names /// - Parameter perLine max numbers of columns per line /// - Returns: a list of columns that can be used in `select` SQL statements -internal func joinedAsSelectedColumns(_ columns: [String], perLine: Int = 3) -> String { +func joinedAsSelectedColumns(_ columns: [String], perLine: Int = 3) -> String { return columns.enumerated().reduce("") { partial, entry in let spacer = entry.offset == 0 || entry.offset % perLine == 0 ? "\n " : " " let isFirstOrLast = entry.offset == 0 || entry.offset >= columns.count diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Update.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Update.swift index 70df1854ec..f409583581 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Update.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+Update.swift @@ -22,9 +22,11 @@ struct UpdateStatement: SQLStatement { self.modelSchema = modelSchema var conditionStatement: ConditionStatement? - if let condition = condition { - let statement = ConditionStatement(modelSchema: modelSchema, - predicate: condition) + if let condition { + let statement = ConditionStatement( + modelSchema: modelSchema, + predicate: condition + ) conditionStatement = statement } @@ -45,7 +47,7 @@ struct UpdateStatement: SQLStatement { where \(modelSchema.primaryKey.columnName()) = ? """ - if let conditionStatement = conditionStatement { + if let conditionStatement { sql = """ \(sql) \(conditionStatement.stringValue) @@ -58,7 +60,7 @@ struct UpdateStatement: SQLStatement { var variables: [Binding?] { var bindings = model.sqlValues(for: updateColumns, modelSchema: modelSchema) bindings.append(model.identifier(schema: modelSchema).stringValue) - if let conditionStatement = conditionStatement { + if let conditionStatement { bindings.append(contentsOf: conditionStatement.variables) } return bindings diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+AnyModel.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+AnyModel.swift index 332e1b8ba6..8e25d4542c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+AnyModel.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+AnyModel.swift @@ -6,26 +6,30 @@ // import Amplify -import SQLite import Foundation +import SQLite extension Statement { - func convertToUntypedModel(using modelSchema: ModelSchema, - statement: SelectStatement, - eagerLoad: Bool) throws -> [Model] { + func convertToUntypedModel( + using modelSchema: ModelSchema, + statement: SelectStatement, + eagerLoad: Bool + ) throws -> [Model] { var models = [Model]() for row in self { - let modelValues = try convert(row: row, - withSchema: modelSchema, - using: statement, - eagerLoad: eagerLoad) + let modelValues = try convert( + row: row, + withSchema: modelSchema, + using: statement, + eagerLoad: eagerLoad + ) let untypedModel = try modelValues.map { try convertToAnyModel(using: modelSchema, modelDictionary: $0) } - if let untypedModel = untypedModel { + if let untypedModel { models.append(untypedModel) } } @@ -33,8 +37,10 @@ extension Statement { return models } - private func convertToAnyModel(using modelSchema: ModelSchema, - modelDictionary: ModelValues) throws -> Model { + private func convertToAnyModel( + using modelSchema: ModelSchema, + modelDictionary: ModelValues + ) throws -> Model { let data = try JSONSerialization.data(withJSONObject: modelDictionary) guard let jsonString = String(data: data, encoding: .utf8) else { let error = DataStoreError.decodingError( diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift index 4345db1a74..58ce7b8234 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore typealias ModelValues = [String: Any?] @@ -39,10 +39,12 @@ protocol StatementModelConvertible { /// - modelSchema - the schema for `Model` /// - statement - the query executed that generated this result /// - Returns: an array of `Model` of the specified type - func convert(to modelType: M.Type, - withSchema modelSchema: ModelSchema, - using statement: SelectStatement, - eagerLoad: Bool) throws -> [M] + func convert( + to modelType: M.Type, + withSchema modelSchema: ModelSchema, + using statement: SelectStatement, + eagerLoad: Bool + ) throws -> [M] } @@ -53,23 +55,29 @@ extension Statement: StatementModelConvertible { Amplify.Logging.logger(forCategory: .dataStore) } - func convert(to modelType: M.Type, - withSchema modelSchema: ModelSchema, - using statement: SelectStatement, - eagerLoad: Bool = true) throws -> [M] { - let elements: [ModelValues] = try self.convertToModelValues(to: modelType, - withSchema: modelSchema, - using: statement, - eagerLoad: eagerLoad) + func convert( + to modelType: M.Type, + withSchema modelSchema: ModelSchema, + using statement: SelectStatement, + eagerLoad: Bool = true + ) throws -> [M] { + let elements: [ModelValues] = try convertToModelValues( + to: modelType, + withSchema: modelSchema, + using: statement, + eagerLoad: eagerLoad + ) let values: ModelValues = ["elements": elements] let result: StatementResult = try StatementResult.from(dictionary: values) return result.elements } - func convertToModelValues(to modelType: M.Type, - withSchema modelSchema: ModelSchema, - using statement: SelectStatement, - eagerLoad: Bool = true) throws -> [ModelValues] { + func convertToModelValues( + to modelType: (some Model).Type, + withSchema modelSchema: ModelSchema, + using statement: SelectStatement, + eagerLoad: Bool = true + ) throws -> [ModelValues] { var elements: [ModelValues] = [] // parse each row of the result @@ -150,7 +158,8 @@ extension Statement: StatementModelConvertible { withSchema: modelSchema, using: statement, eagerLoad: eagerLoad, - path: path + [field.name]) + path: path + [field.name] + ) default: let value = getValue(from: element, by: path + [field.name]) @@ -159,41 +168,45 @@ extension Statement: StatementModelConvertible { } private func getModelSchema(for modelName: ModelName, with statement: SelectStatement) -> ModelSchema? { - return statement.metadata.columnMapping.values.first { $0.0.name == modelName }.map { $0.0 } + return statement.metadata.columnMapping.values.first { $0.0.name == modelName }.map(\.0) } private func associatedValues(from foreignKeyPath: [String], element: Element) -> [String] { return [getValue(from: element, by: foreignKeyPath)] - .compactMap({ $0 }) - .map({ String(describing: $0) }) - .flatMap({ $0.split(separator: ModelIdentifierFormat.Custom.separator.first!) }) - .map({ String($0).trimmingCharacters(in: .init(charactersIn: "\"")) }) + .compactMap { $0 } + .map { String(describing: $0) } + .flatMap { $0.split(separator: ModelIdentifierFormat.Custom.separator.first!) } + .map { String($0).trimmingCharacters(in: .init(charactersIn: "\"")) } } private func convertCollection(field: ModelField, schema: ModelSchema, from element: Element, path: [String]) -> Any? { if field.isArray && field.hasAssociation, case let .some(.hasMany(associatedFieldName: associatedFieldName, associatedFieldNames: associatedFieldNames)) = field.association { // Construct the lazy list based on the field reference name and `@@primarykey` or primary key field of the parent - if associatedFieldNames.count <= 1, let associatedFieldName = associatedFieldName { + if associatedFieldNames.count <= 1, let associatedFieldName { let primaryKeyName = schema.primaryKey.isCompositeKey ? ModelIdentifierFormat.Custom.sqlColumnName - : schema.primaryKey.fields.first.flatMap { $0.name } + : schema.primaryKey.fields.first.flatMap{ $0.name } let primaryKeyValue = primaryKeyName.flatMap { getValue(from: element, by: path + [$0]) } return primaryKeyValue.map { - DataStoreListDecoder.lazyInit(associatedIds: [String(describing: $0)], - associatedWith: [associatedFieldName]) + DataStoreListDecoder.lazyInit( + associatedIds: [String(describing: $0)], + associatedWith: [associatedFieldName] + ) } } else { // If `targetNames` is > 1, then this is a uni-directional has-many, thus no reference field on the child // Construct the lazy list based on the primary key values and the corresponding target names - let primaryKeyNames = schema.primaryKey.fields.map { $0.name } + let primaryKeyNames = schema.primaryKey.fields.map(\.name) let primaryKeyValues = primaryKeyNames .map { getValue(from: element, by: path + [$0]) } .compactMap { $0 } .map { String(describing: $0) } - return DataStoreListDecoder.lazyInit(associatedIds: primaryKeyValues, - associatedWith: associatedFieldNames) + return DataStoreListDecoder.lazyInit( + associatedIds: primaryKeyValues, + associatedWith: associatedFieldNames + ) } } @@ -231,7 +244,7 @@ extension Statement: StatementModelConvertible { } } -private extension Dictionary where Key == String, Value == Any? { +private extension [String: Any?] { /// Utility to create a `NSMutableDictionary` from a Swift `Dictionary`. func mutableCopy() -> NSMutableDictionary { @@ -325,8 +338,8 @@ extension String { } } -extension Array where Element == String { +extension [String] { var fieldPath: String { - self.filter { !$0.isEmpty }.joined(separator: ".") + filter { !$0.isEmpty }.joined(separator: ".") } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift index d01c94bacb..ab088b52c4 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Foundation import SQLite -import AWSPluginsCore // swiftlint:disable type_body_length file_length /// [SQLite](https://sqlite.org) `StorageEngineAdapter` implementation. This class provides @@ -27,9 +27,11 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { // our system and find an optimal value. static var maxNumberOfPredicates: Int = 950 - convenience init(version: String, - databaseName: String = "database", - userDefaults: UserDefaults = UserDefaults.standard) throws { + convenience init( + version: String, + databaseName: String = "database", + userDefaults: UserDefaults = UserDefaults.standard + ) throws { var dbFilePath = SQLiteStorageEngineAdapter.getDbFilePath(databaseName: databaseName) _ = try SQLiteStorageEngineAdapter.clearIfNewVersion(version: version, dbFilePath: dbFilePath) @@ -46,17 +48,21 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { throw DataStoreError.invalidDatabase(path: path, error) } - try self.init(connection: connection, - dbFilePath: dbFilePath, - userDefaults: userDefaults, - version: version) + try self.init( + connection: connection, + dbFilePath: dbFilePath, + userDefaults: userDefaults, + version: version + ) } - internal init(connection: Connection, - dbFilePath: URL? = nil, - userDefaults: UserDefaults = UserDefaults.standard, - version: String = "version") throws { + init( + connection: Connection, + dbFilePath: URL? = nil, + userDefaults: UserDefaults = UserDefaults.standard, + version: String = "version" + ) throws { self.connection = connection self.dbFilePath = dbFilePath try SQLiteStorageEngineAdapter.initializeDatabase(connection: connection) @@ -89,7 +95,7 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } func setUp(modelSchemas: [ModelSchema]) throws { - guard let connection = connection else { + guard let connection else { throw DataStoreError.invalidOperation(causedBy: nil) } @@ -117,13 +123,16 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { func applyModelMigrations(modelSchemas: [ModelSchema]) throws { let delegate = SQLiteMutationSyncMetadataMigrationDelegate( storageAdapter: self, - modelSchemas: modelSchemas) + modelSchemas: modelSchemas + ) let mutationSyncMetadataMigration = MutationSyncMetadataMigration(delegate: delegate) let modelSyncMetadataMigration = ModelSyncMetadataMigration(storageAdapter: self) - let modelMigrations = ModelMigrations(modelMigrations: [mutationSyncMetadataMigration, - modelSyncMetadataMigration]) + let modelMigrations = ModelMigrations(modelMigrations: [ + mutationSyncMetadataMigration, + modelSyncMetadataMigration + ]) do { try modelMigrations.apply() } catch { @@ -132,33 +141,43 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } // MARK: - Save - func save(_ model: M, - condition: QueryPredicate? = nil, - eagerLoad: Bool = true, - completion: @escaping DataStoreCallback) { - save(model, - modelSchema: model.schema, - condition: condition, - eagerLoad: eagerLoad, - completion: completion) + func save( + _ model: M, + condition: QueryPredicate? = nil, + eagerLoad: Bool = true, + completion: @escaping DataStoreCallback + ) { + save( + model, + modelSchema: model.schema, + condition: condition, + eagerLoad: eagerLoad, + completion: completion + ) } - func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate? = nil, - eagerLoad: Bool = true, - completion: DataStoreCallback) { - completion(save(model, - modelSchema: modelSchema, - condition: condition, - eagerLoad: eagerLoad)) + func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate? = nil, + eagerLoad: Bool = true, + completion: DataStoreCallback + ) { + completion(save( + model, + modelSchema: modelSchema, + condition: condition, + eagerLoad: eagerLoad + )) } - func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate? = nil, - eagerLoad: Bool = true) -> DataStoreResult { - guard let connection = connection else { + func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate? = nil, + eagerLoad: Bool = true + ) -> DataStoreResult { + guard let connection else { return .failure(DataStoreError.nilSQLiteConnection()) } do { @@ -167,10 +186,11 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { let modelExists = try exists(modelSchema, withIdentifier: modelIdentifier) if !modelExists { - if let condition = condition, !condition.isAll { + if let condition, !condition.isAll { let dataStoreError = DataStoreError.invalidCondition( "Cannot apply a condition on model which does not exist.", - "Save the model instance without a condition first.") + "Save the model instance without a condition first." + ) return .failure(causedBy: dataStoreError) } @@ -179,35 +199,45 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } if modelExists { - if let condition = condition, !condition.isAll { - let modelExistsWithCondition = try exists(modelSchema, - withIdentifier: modelIdentifier, - predicate: condition) + if let condition, !condition.isAll { + let modelExistsWithCondition = try exists( + modelSchema, + withIdentifier: modelIdentifier, + predicate: condition + ) if !modelExistsWithCondition { let dataStoreError = DataStoreError.invalidCondition( - "Save failed due to condition did not match existing model instance.", - "The save will continue to fail until the model instance is updated.") + "Save failed due to condition did not match existing model instance.", + "The save will continue to fail until the model instance is updated." + ) return .failure(causedBy: dataStoreError) } } - let statement = UpdateStatement(model: model, - modelSchema: modelSchema, - condition: condition) + let statement = UpdateStatement( + model: model, + modelSchema: modelSchema, + condition: condition + ) _ = try connection.prepare(statement.stringValue).run(statement.variables) } // load the recent saved instance and pass it back to the callback - let queryResult = query(modelType, modelSchema: modelSchema, - predicate: model.identifier(schema: modelSchema).predicate, - eagerLoad: eagerLoad) + let queryResult = query( + modelType, + modelSchema: modelSchema, + predicate: model.identifier(schema: modelSchema).predicate, + eagerLoad: eagerLoad + ) switch queryResult { case .success(let result): if let saved = result.first { return .success(saved) } else { - return .failure(.nonUniqueResult(model: modelType.modelName, - count: result.count)) + return .failure(.nonUniqueResult( + model: modelType.modelName, + count: result.count + )) } case .failure(let error): return .failure(error) @@ -218,11 +248,13 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } // MARK: - Delete - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: (DataStoreResult<[M]>) -> Void) { - guard let connection = connection else { + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: (DataStoreResult<[M]>) -> Void + ) { + guard let connection else { completion(.failure(DataStoreError.nilSQLiteConnection())) return } @@ -235,15 +267,19 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: Model.Identifier, - condition: QueryPredicate? = nil, - completion: (DataStoreResult) -> Void) { - delete(untypedModelType: modelType, - modelSchema: modelSchema, - withId: id, - condition: condition) { result in + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: Model.Identifier, + condition: QueryPredicate? = nil, + completion: (DataStoreResult) -> Void + ) { + delete( + untypedModelType: modelType, + modelSchema: modelSchema, + withId: id, + condition: condition + ) { result in switch result { case .success: completion(.success(nil)) @@ -253,15 +289,19 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) where M: Model { - delete(untypedModelType: modelType, - modelSchema: modelSchema, - withIdentifier: identifier, - condition: condition) { result in + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) where M: Model { + delete( + untypedModelType: modelType, + modelSchema: modelSchema, + withIdentifier: identifier, + condition: condition + ) { result in switch result { case .success: completion(.success(nil)) @@ -271,31 +311,39 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } } - func delete(untypedModelType modelType: Model.Type, - modelSchema: ModelSchema, - withId id: Model.Identifier, - condition: QueryPredicate? = nil, - completion: DataStoreCallback) { - delete(untypedModelType: modelType, - modelSchema: modelSchema, - withIdentifier: DefaultModelIdentifier.makeDefault(id: id), - condition: condition, - completion: completion) + func delete( + untypedModelType modelType: Model.Type, + modelSchema: ModelSchema, + withId id: Model.Identifier, + condition: QueryPredicate? = nil, + completion: DataStoreCallback + ) { + delete( + untypedModelType: modelType, + modelSchema: modelSchema, + withIdentifier: DefaultModelIdentifier.makeDefault(id: id), + condition: condition, + completion: completion + ) } - func delete(untypedModelType modelType: Model.Type, - modelSchema: ModelSchema, - withIdentifier id: ModelIdentifierProtocol, - condition: QueryPredicate? = nil, - completion: DataStoreCallback) { - guard let connection = connection else { + func delete( + untypedModelType modelType: Model.Type, + modelSchema: ModelSchema, + withIdentifier id: ModelIdentifierProtocol, + condition: QueryPredicate? = nil, + completion: DataStoreCallback + ) { + guard let connection else { completion(.failure(DataStoreError.nilSQLiteConnection())) return } do { - let statement = DeleteStatement(modelSchema: modelSchema, - withIdentifier: id, - predicate: condition) + let statement = DeleteStatement( + modelSchema: modelSchema, + withIdentifier: id, + predicate: condition + ) _ = try connection.prepare(statement.stringValue).run(statement.variables) completion(.emptyResult) } catch { @@ -304,56 +352,70 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } // MARK: - query - func query(_ modelType: M.Type, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true, - completion: DataStoreCallback<[M]>) { - query(modelType, - modelSchema: modelType.schema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad, - completion: completion) + func query( + _ modelType: M.Type, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true, + completion: DataStoreCallback<[M]> + ) { + query( + modelType, + modelSchema: modelType.schema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad, + completion: completion + ) } - func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true, - completion: DataStoreCallback<[M]>) { - completion(query(modelType, - modelSchema: modelSchema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad)) + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true, + completion: DataStoreCallback<[M]> + ) { + completion(query( + modelType, + modelSchema: modelSchema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad + )) } - private func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true) -> DataStoreResult<[M]> { - guard let connection = connection else { + private func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true + ) -> DataStoreResult<[M]> { + guard let connection else { return .failure(DataStoreError.nilSQLiteConnection()) } do { - let statement = SelectStatement(from: modelSchema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad) + let statement = SelectStatement( + from: modelSchema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad + ) let rows = try connection.prepare(statement.stringValue).run(statement.variables) - let result: [M] = try rows.convert(to: modelType, - withSchema: modelSchema, - using: statement, - eagerLoad: eagerLoad) + let result: [M] = try rows.convert( + to: modelType, + withSchema: modelSchema, + using: statement, + eagerLoad: eagerLoad + ) return .success(result) } catch { return .failure(causedBy: error) @@ -361,24 +423,30 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } // MARK: - Exists - func exists(_ modelSchema: ModelSchema, - withId id: String, - predicate: QueryPredicate? = nil) throws -> Bool { - try exists(modelSchema, - withIdentifier: DefaultModelIdentifier.makeDefault(id: id), - predicate: predicate) + func exists( + _ modelSchema: ModelSchema, + withId id: String, + predicate: QueryPredicate? = nil + ) throws -> Bool { + try exists( + modelSchema, + withIdentifier: DefaultModelIdentifier.makeDefault(id: id), + predicate: predicate + ) } - func exists(_ modelSchema: ModelSchema, - withIdentifier id: ModelIdentifierProtocol, - predicate: QueryPredicate? = nil) throws -> Bool { - guard let connection = connection else { + func exists( + _ modelSchema: ModelSchema, + withIdentifier id: ModelIdentifierProtocol, + predicate: QueryPredicate? = nil + ) throws -> Bool { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let primaryKey = modelSchema.primaryKey.sqlName.quoted() var sql = "select count(\(primaryKey)) from \"\(modelSchema.name)\" where \(primaryKey) = ?" var variables: [Binding?] = [id.stringValue] - if let predicate = predicate { + if let predicate { let conditionStatement = ConditionStatement(modelSchema: modelSchema, predicate: predicate) sql = """ \(sql) @@ -405,7 +473,7 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } func queryMutationSync(for models: [Model], modelName: String) throws -> [MutationSync] { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } @@ -422,15 +490,19 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { // group models by id for fast access when creating the tuple let modelById = Dictionary(grouping: models, by: { - return MutationSyncMetadata.identifier(modelName: modelName, - modelId: $0.identifier(schema: modelSchema).stringValue) + return MutationSyncMetadata.identifier( + modelName: modelName, + modelId: $0.identifier(schema: modelSchema).stringValue + ) }).mapValues { $0.first! } let ids = [String](modelById.keys) let rows = try connection.prepare(sql).bind(ids) - let syncMetadataList = try rows.convert(to: MutationSyncMetadata.self, - withSchema: MutationSyncMetadata.schema, - using: statement) + let syncMetadataList = try rows.convert( + to: MutationSyncMetadata.self, + withSchema: MutationSyncMetadata.schema, + using: statement + ) let mutationSyncList = try syncMetadataList.map { syncMetadata -> MutationSync in guard let model = modelById[syncMetadata.id] else { throw DataStoreError.invalidOperation(causedBy: nil) @@ -446,9 +518,11 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { return try results.unique() } - func queryMutationSyncMetadata(for modelIds: [String], - modelName: String) throws -> [MutationSyncMetadata] { - guard let connection = connection else { + func queryMutationSyncMetadata( + for modelIds: [String], + modelName: String + ) throws -> [MutationSyncMetadata] { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let modelType = MutationSyncMetadata.self @@ -459,37 +533,47 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { for chunkedModelIds in chunkedModelIdsArr { var queryPredicates: [QueryPredicateOperation] = [] for id in chunkedModelIds { - let mutationSyncMetadataId = MutationSyncMetadata.identifier(modelName: modelName, - modelId: id) - queryPredicates.append(QueryPredicateOperation(field: fields.id.stringValue, - operator: .equals(mutationSyncMetadataId))) + let mutationSyncMetadataId = MutationSyncMetadata.identifier( + modelName: modelName, + modelId: id + ) + queryPredicates.append(QueryPredicateOperation( + field: fields.id.stringValue, + operator: .equals(mutationSyncMetadataId) + )) } let groupedQueryPredicates = QueryPredicateGroup(type: .or, predicates: queryPredicates) let statement = SelectStatement(from: modelSchema, predicate: groupedQueryPredicates) let rows = try connection.prepare(statement.stringValue).run(statement.variables) - let result = try rows.convert(to: modelType, - withSchema: modelSchema, - using: statement) + let result = try rows.convert( + to: modelType, + withSchema: modelSchema, + using: statement + ) results.append(contentsOf: result) } return results } func queryModelSyncMetadata(for modelSchema: ModelSchema) throws -> ModelSyncMetadata? { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } - let statement = SelectStatement(from: ModelSyncMetadata.schema, - predicate: field("id").eq(modelSchema.name)) + let statement = SelectStatement( + from: ModelSyncMetadata.schema, + predicate: field("id").eq(modelSchema.name) + ) let rows = try connection.prepare(statement.stringValue).run(statement.variables) - let result = try rows.convert(to: ModelSyncMetadata.self, - withSchema: ModelSyncMetadata.schema, - using: statement) + let result = try rows.convert( + to: ModelSyncMetadata.self, + withSchema: ModelSyncMetadata.schema, + using: statement + ) return try result.unique() } func transaction(_ transactionBlock: BasicThrowableClosure) throws { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } try connection.transaction { @@ -498,7 +582,7 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } func clear(completion: @escaping DataStoreCallback) { - guard let dbFilePath = dbFilePath else { + guard let dbFilePath else { log.error("Attempt to clear DB, but file path was empty") completion(.failure(causedBy: DataStoreError.invalidDatabase(path: "Database path not set", nil))) return @@ -523,10 +607,12 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { return false } - static func clearIfNewVersion(version: String, - dbFilePath: URL, - userDefaults: UserDefaults = UserDefaults.standard, - fileManager: FileManager = FileManager.default) throws -> Bool { + static func clearIfNewVersion( + version: String, + dbFilePath: URL, + userDefaults: UserDefaults = UserDefaults.standard, + fileManager: FileManager = FileManager.default + ) throws -> Bool { guard let previousVersion = userDefaults.string(forKey: dbVersionKey) else { return false @@ -569,11 +655,14 @@ private func getDocumentPath() -> URL? { extension DataStoreError { static func nilSQLiteConnection() -> DataStoreError { - .internalOperation("SQLite connection is `nil`", + .internalOperation( + "SQLite connection is `nil`", """ This is expected if DataStore.clear is called while syncing as the SQLite connection is closed. Call DataStore.start to restart the sync process. - """, nil) + """, + nil + ) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift index 212840733f..7acc4e2ae8 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift @@ -10,21 +10,22 @@ import SQLite extension SQLiteStorageEngineAdapter { - func save(untypedModel: Model, - eagerLoad: Bool = true, - completion: DataStoreCallback) { - guard let connection = connection else { + func save( + untypedModel: Model, + eagerLoad: Bool = true, + completion: DataStoreCallback + ) { + guard let connection else { completion(.failure(.nilSQLiteConnection())) return } do { - let modelName: ModelName - if let jsonModel = untypedModel as? JSONValueHolder, + let modelName: ModelName = if let jsonModel = untypedModel as? JSONValueHolder, let modelNameFromJson = jsonModel.jsonValue(for: "__typename") as? String { - modelName = modelNameFromJson + modelNameFromJson } else { - modelName = untypedModel.modelName + untypedModel.modelName } guard let modelSchema = ModelRegistry.modelSchema(from: modelName) else { @@ -32,8 +33,10 @@ extension SQLiteStorageEngineAdapter { throw error } - let shouldUpdate = try exists(modelSchema, - withIdentifier: untypedModel.identifier(schema: modelSchema)) + let shouldUpdate = try exists( + modelSchema, + withIdentifier: untypedModel.identifier(schema: modelSchema) + ) if shouldUpdate { let statement = UpdateStatement(model: untypedModel, modelSchema: modelSchema) @@ -43,16 +46,20 @@ extension SQLiteStorageEngineAdapter { _ = try connection.prepare(statement.stringValue).run(statement.variables) } - query(modelSchema: modelSchema, - predicate: untypedModel.identifier(schema: modelSchema).predicate, - eagerLoad: eagerLoad) { + query( + modelSchema: modelSchema, + predicate: untypedModel.identifier(schema: modelSchema).predicate, + eagerLoad: eagerLoad + ) { switch $0 { case .success(let result): if let saved = result.first { completion(.success(saved)) } else { - completion(.failure(.nonUniqueResult(model: modelSchema.name, - count: result.count))) + completion(.failure(.nonUniqueResult( + model: modelSchema.name, + count: result.count + ))) } case .failure(let error): completion(.failure(error)) @@ -64,22 +71,28 @@ extension SQLiteStorageEngineAdapter { } } - func query(modelSchema: ModelSchema, - predicate: QueryPredicate? = nil, - eagerLoad: Bool = true, - completion: DataStoreCallback<[Model]>) { - guard let connection = connection else { + func query( + modelSchema: ModelSchema, + predicate: QueryPredicate? = nil, + eagerLoad: Bool = true, + completion: DataStoreCallback<[Model]> + ) { + guard let connection else { completion(.failure(.nilSQLiteConnection())) return } do { - let statement = SelectStatement(from: modelSchema, - predicate: predicate, - eagerLoad: eagerLoad) + let statement = SelectStatement( + from: modelSchema, + predicate: predicate, + eagerLoad: eagerLoad + ) let rows = try connection.prepare(statement.stringValue).run(statement.variables) - let result: [Model] = try rows.convertToUntypedModel(using: modelSchema, - statement: statement, - eagerLoad: eagerLoad) + let result: [Model] = try rows.convertToUntypedModel( + using: modelSchema, + statement: statement, + eagerLoad: eagerLoad + ) completion(.success(result)) } catch { completion(.failure(causedBy: error)) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineMigrationAdapter+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineMigrationAdapter+SQLite.swift index 42370a1be2..a1ecd849ea 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineMigrationAdapter+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineMigrationAdapter+SQLite.swift @@ -12,7 +12,7 @@ import SQLite extension SQLiteStorageEngineAdapter { @discardableResult func createStore(for modelSchema: ModelSchema) throws -> String { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let createTableStatement = CreateTableStatement(modelSchema: modelSchema).stringValue @@ -23,7 +23,7 @@ extension SQLiteStorageEngineAdapter { } @discardableResult func removeStore(for modelSchema: ModelSchema) throws -> String { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let dropStatement = DropTableStatement(modelSchema: modelSchema).stringValue @@ -32,7 +32,7 @@ extension SQLiteStorageEngineAdapter { } @discardableResult func emptyStore(for modelSchema: ModelSchema) throws -> String { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let deleteStatement = DeleteStatement(modelSchema: modelSchema).stringValue @@ -41,7 +41,7 @@ extension SQLiteStorageEngineAdapter { } @discardableResult func renameStore(from: ModelSchema, toModelSchema: ModelSchema) throws -> String { - guard let connection = connection else { + guard let connection else { throw DataStoreError.nilSQLiteConnection() } let alterTableStatement = AlterTableStatement(from: from, toModelSchema: toModelSchema).stringValue diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine+SyncRequirement.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine+SyncRequirement.swift index b6a8aac20c..3f137c0d0d 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine+SyncRequirement.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine+SyncRequirement.swift @@ -6,16 +6,16 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore extension StorageEngine { func startSync() -> Result { let (result, syncEngine) = initalizeSyncEngine() - if let syncEngine = syncEngine, !syncEngine.isSyncing() { + if let syncEngine, !syncEngine.isSyncing() { guard let api = tryGetAPIPlugin() else { log.info("Unable to find suitable API plugin for syncEngine. syncEngine will not be started") return .failure(.configuration( @@ -59,16 +59,16 @@ extension StorageEngine { } private func initalizeSyncEngine() -> (SyncEngineInitResult, RemoteSyncEngineBehavior?) { - if let syncEngine = syncEngine { + if let syncEngine { return (.alreadyInitialized, syncEngine) } else { if isSyncEnabled, syncEngine == nil { - self.syncEngine = try? RemoteSyncEngine( + syncEngine = try? RemoteSyncEngine( storageAdapter: storageAdapter, dataStoreConfiguration: dataStoreConfiguration ) - self.syncEngineSink = syncEngine?.publisher.sink( + syncEngineSink = syncEngine?.publisher.sink( receiveCompletion: onReceiveCompletion(receiveCompletion:), receiveValue: onReceive(receiveValue:) ) @@ -107,9 +107,11 @@ extension StorageEngine { guard schema.isSyncable else { return false } - return requiresAuthPlugin(apiPlugin, - authRules: schema.authRules, - authModeStrategy: authModeStrategy) + return requiresAuthPlugin( + apiPlugin, + authRules: schema.authRules, + authModeStrategy: authModeStrategy + ) } return modelsRequireAuthPlugin @@ -175,7 +177,7 @@ extension StorageEngine { } } -internal extension AuthRules { +extension AuthRules { /// Convenience method to check whether we need Auth plugin /// - Returns: true If **any** of the rules uses a provider that requires the Auth plugin, `nil` otherwise var requireAuthPlugin: Bool? { @@ -191,9 +193,9 @@ internal extension AuthRules { } } -internal extension AuthRule { +extension AuthRule { var requiresAuthPlugin: Bool? { - guard let provider = self.provider else { + guard let provider else { return nil } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine.swift index 53c213e4fb..9ba91c2bec 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngine.swift @@ -6,17 +6,19 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore typealias StorageEngineBehaviorFactory = - (Bool, - DataStoreConfiguration, - String, - String, - String, - UserDefaults) throws -> StorageEngineBehavior + ( + Bool, + DataStoreConfiguration, + String, + String, + String, + UserDefaults + ) throws -> StorageEngineBehavior // swiftlint:disable type_body_length final class StorageEngine: StorageEngineBehavior { @@ -72,12 +74,13 @@ final class StorageEngine: StorageEngineBehavior { // Internal initializer used for testing, to allow lazy initialization of the SyncEngine. Note that the provided // storageAdapter must have already been set up with system models - init(storageAdapter: StorageEngineAdapter, - dataStoreConfiguration: DataStoreConfiguration, - syncEngine: RemoteSyncEngineBehavior?, - validAPIPluginKey: String, - validAuthPluginKey: String, - isSyncEnabled: Bool = false + init( + storageAdapter: StorageEngineAdapter, + dataStoreConfiguration: DataStoreConfiguration, + syncEngine: RemoteSyncEngineBehavior?, + validAPIPluginKey: String, + validAuthPluginKey: String, + isSyncEnabled: Bool = false ) { self.storageAdapter = storageAdapter self.dataStoreConfiguration = dataStoreConfiguration @@ -91,12 +94,14 @@ final class StorageEngine: StorageEngineBehavior { self.operationQueue = operationQueue } - convenience init(isSyncEnabled: Bool, - dataStoreConfiguration: DataStoreConfiguration, - validAPIPluginKey: String = "awsAPIPlugin", - validAuthPluginKey: String = "awsCognitoAuthPlugin", - modelRegistryVersion: String, - userDefault: UserDefaults = UserDefaults.standard) throws { + convenience init( + isSyncEnabled: Bool, + dataStoreConfiguration: DataStoreConfiguration, + validAPIPluginKey: String = "awsAPIPlugin", + validAuthPluginKey: String = "awsCognitoAuthPlugin", + modelRegistryVersion: String, + userDefault: UserDefaults = UserDefaults.standard + ) throws { let key = kCFBundleNameKey as String let databaseName = Bundle.main.object(forInfoDictionaryKey: key) as? String ?? "app" @@ -179,19 +184,23 @@ final class StorageEngine: StorageEngineBehavior { try storageAdapter.applyModelMigrations(modelSchemas: modelSchemas) } - public func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate? = nil, - eagerLoad: Bool = true, - completion: @escaping DataStoreCallback) { + public func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate? = nil, + eagerLoad: Bool = true, + completion: @escaping DataStoreCallback + ) { // TODO: Refactor this into a proper request/result where the result includes metadata like the derived // mutation type let modelExists: Bool do { - modelExists = try storageAdapter.exists(modelSchema, - withIdentifier: model.identifier(schema: modelSchema), - predicate: nil) + modelExists = try storageAdapter.exists( + modelSchema, + withIdentifier: model.identifier(schema: modelSchema), + predicate: nil + ) } catch { let dataStoreError = DataStoreError.invalidOperation(causedBy: error) completion(.failure(dataStoreError)) @@ -201,20 +210,23 @@ final class StorageEngine: StorageEngineBehavior { let mutationType = modelExists ? MutationEvent.MutationType.update : .create // If it is `create`, and there is a condition, and that condition is not `.all`, fail the request - if mutationType == .create, let condition = condition, !condition.isAll { + if mutationType == .create, let condition, !condition.isAll { let dataStoreError = DataStoreError.invalidCondition( "Cannot apply a condition on model which does not exist.", - "Save the model instance without a condition first.") + "Save the model instance without a condition first." + ) completion(.failure(causedBy: dataStoreError)) return } do { try storageAdapter.transaction { - let result = self.storageAdapter.save(model, - modelSchema: modelSchema, - condition: condition, - eagerLoad: eagerLoad) + let result = self.storageAdapter.save( + model, + modelSchema: modelSchema, + condition: condition, + eagerLoad: eagerLoad + ) guard modelSchema.isSyncable else { completion(result) return @@ -231,105 +243,134 @@ final class StorageEngine: StorageEngineBehavior { throw DataStoreError.internalOperation( message, "`DataStore.save()` was interrupted. `DataStore.stop()` may have been called.", - nil) + nil + ) } self.log.verbose("\(#function) syncing mutation for \(savedModel)") - self.syncMutation(of: savedModel, - modelSchema: modelSchema, - mutationType: mutationType, - predicate: condition, - syncEngine: syncEngine, - completion: completion) + self.syncMutation( + of: savedModel, + modelSchema: modelSchema, + mutationType: mutationType, + predicate: condition, + syncEngine: syncEngine, + completion: completion + ) } } catch { completion(.failure(causedBy: error)) } } - func save(_ model: M, - condition: QueryPredicate? = nil, - eagerLoad: Bool = true, - completion: @escaping DataStoreCallback) { - save(model, - modelSchema: model.schema, - condition: condition, - eagerLoad: eagerLoad, - completion: completion) + func save( + _ model: M, + condition: QueryPredicate? = nil, + eagerLoad: Bool = true, + completion: @escaping DataStoreCallback + ) { + save( + model, + modelSchema: model.schema, + condition: condition, + eagerLoad: eagerLoad, + completion: completion + ) } @available(*, deprecated, message: "Use delete(:modelSchema:withIdentifier:predicate:completion") - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: Model.Identifier, - condition: QueryPredicate? = nil, - completion: @escaping (DataStoreResult) -> Void) { - let cascadeDeleteOperation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: modelType, modelSchema: modelSchema, - withIdentifier: DefaultModelIdentifier.makeDefault(id: id), - condition: condition) { completion($0) } + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: Model.Identifier, + condition: QueryPredicate? = nil, + completion: @escaping (DataStoreResult) -> Void + ) { + let cascadeDeleteOperation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: modelType, + modelSchema: modelSchema, + withIdentifier: DefaultModelIdentifier.makeDefault(id: id), + condition: condition + ) { completion($0) } operationQueue.addOperation(cascadeDeleteOperation) } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) { - let cascadeDeleteOperation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: modelType, modelSchema: modelSchema, - withIdentifier: identifier, - condition: condition) { completion($0) } + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) { + let cascadeDeleteOperation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: modelType, + modelSchema: modelSchema, + withIdentifier: identifier, + condition: condition + ) { completion($0) } operationQueue.addOperation(cascadeDeleteOperation) } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) { - let cascadeDeleteOperation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: modelType, - modelSchema: modelSchema, - filter: filter) { completion($0) } + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) { + let cascadeDeleteOperation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: modelType, + modelSchema: modelSchema, + filter: filter + ) { completion($0) } operationQueue.addOperation(cascadeDeleteOperation) } - func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool = true, - completion: (DataStoreResult<[M]>) -> Void) { - return storageAdapter.query(modelType, - modelSchema: modelSchema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad, - completion: completion) + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool = true, + completion: (DataStoreResult<[M]>) -> Void + ) { + return storageAdapter.query( + modelType, + modelSchema: modelSchema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad, + completion: completion + ) } - func query(_ modelType: M.Type, - predicate: QueryPredicate? = nil, - sort: [QuerySortDescriptor]? = nil, - paginationInput: QueryPaginationInput? = nil, - eagerLoad: Bool = true, - completion: DataStoreCallback<[M]>) { - query(modelType, - modelSchema: modelType.schema, - predicate: predicate, - sort: sort, - paginationInput: paginationInput, - eagerLoad: eagerLoad, - completion: completion) + func query( + _ modelType: M.Type, + predicate: QueryPredicate? = nil, + sort: [QuerySortDescriptor]? = nil, + paginationInput: QueryPaginationInput? = nil, + eagerLoad: Bool = true, + completion: DataStoreCallback<[M]> + ) { + query( + modelType, + modelSchema: modelType.schema, + predicate: predicate, + sort: sort, + paginationInput: paginationInput, + eagerLoad: eagerLoad, + completion: completion + ) } func clear(completion: @escaping DataStoreCallback) { - if let syncEngine = syncEngine { + if let syncEngine { syncEngine.stop(completion: { _ in self.syncEngine = nil self.storageAdapter.clear(completion: completion) @@ -340,7 +381,7 @@ final class StorageEngine: StorageEngineBehavior { } func stopSync(completion: @escaping DataStoreCallback) { - if let syncEngine = syncEngine { + if let syncEngine { syncEngine.stop { _ in self.syncEngine = nil completion(.successfulVoid) @@ -351,24 +392,30 @@ final class StorageEngine: StorageEngineBehavior { } @available(iOS 13.0, *) - private func syncMutation(of savedModel: M, - modelSchema: ModelSchema, - mutationType: MutationEvent.MutationType, - predicate: QueryPredicate? = nil, - syncEngine: RemoteSyncEngineBehavior, - completion: @escaping DataStoreCallback) { + private func syncMutation( + of savedModel: M, + modelSchema: ModelSchema, + mutationType: MutationEvent.MutationType, + predicate: QueryPredicate? = nil, + syncEngine: RemoteSyncEngineBehavior, + completion: @escaping DataStoreCallback + ) { let mutationEvent: MutationEvent do { var graphQLFilterJSON: String? - if let predicate = predicate { - graphQLFilterJSON = try GraphQLFilterConverter.toJSON(predicate, - modelSchema: modelSchema) + if let predicate { + graphQLFilterJSON = try GraphQLFilterConverter.toJSON( + predicate, + modelSchema: modelSchema + ) } - mutationEvent = try MutationEvent(model: savedModel, - modelSchema: modelSchema, - mutationType: mutationType, - graphQLFilterJSON: graphQLFilterJSON) + mutationEvent = try MutationEvent( + model: savedModel, + modelSchema: modelSchema, + mutationType: mutationType, + graphQLFilterJSON: graphQLFilterJSON + ) } catch { let dataStoreError = DataStoreError(error: error) @@ -386,14 +433,18 @@ final class StorageEngine: StorageEngineBehavior { } } - submitToSyncEngine(mutationEvent: mutationEvent, - syncEngine: syncEngine, - completion: mutationEventCallback) + submitToSyncEngine( + mutationEvent: mutationEvent, + syncEngine: syncEngine, + completion: mutationEventCallback + ) } - private func submitToSyncEngine(mutationEvent: MutationEvent, - syncEngine: RemoteSyncEngineBehavior, - completion: @escaping DataStoreCallback) { + private func submitToSyncEngine( + mutationEvent: MutationEvent, + syncEngine: RemoteSyncEngineBehavior, + completion: @escaping DataStoreCallback + ) { Task { syncEngine.submit(mutationEvent, completion: completion) } @@ -407,7 +458,7 @@ extension StorageEngine: Resettable { if let resettable = syncEngine as? Resettable { log.verbose("Resetting syncEngine") await resettable.reset() - self.log.verbose("Resetting syncEngine: finished") + log.verbose("Resetting syncEngine: finished") } } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift index 191df26ebc..448020b80f 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSPluginsCore +import Foundation protocol StorageEngineAdapter: AnyObject, ModelStorageBehavior, ModelStorageErrorBehavior, StorageEngineMigrationAdapter { @@ -16,32 +16,42 @@ protocol StorageEngineAdapter: AnyObject, ModelStorageBehavior, ModelStorageErro // MARK: - Async APIs func save(untypedModel: Model, eagerLoad: Bool, completion: @escaping DataStoreCallback) - func delete(untypedModelType modelType: Model.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: DataStoreCallback) - - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) - - func query(modelSchema: ModelSchema, - predicate: QueryPredicate?, - eagerLoad: Bool, - completion: DataStoreCallback<[Model]>) + func delete( + untypedModelType modelType: Model.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: DataStoreCallback + ) + + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) + + func query( + modelSchema: ModelSchema, + predicate: QueryPredicate?, + eagerLoad: Bool, + completion: DataStoreCallback<[Model]> + ) // MARK: - Synchronous APIs - func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate?, - eagerLoad: Bool) -> DataStoreResult + func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate?, + eagerLoad: Bool + ) -> DataStoreResult - func exists(_ modelSchema: ModelSchema, - withIdentifier id: ModelIdentifierProtocol, - predicate: QueryPredicate?) throws -> Bool + func exists( + _ modelSchema: ModelSchema, + withIdentifier id: ModelIdentifierProtocol, + predicate: QueryPredicate? + ) throws -> Bool func queryMutationSync(for models: [Model], modelName: String) throws -> [MutationSync] @@ -71,20 +81,26 @@ protocol StorageEngineMigrationAdapter { extension StorageEngineAdapter { - func delete(_ modelType: M.Type, - filter predicate: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) { + func delete( + _ modelType: M.Type, + filter predicate: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) { delete(modelType, modelSchema: modelType.schema, filter: predicate, completion: completion) } - func delete(untypedModelType modelType: Model.Type, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate? = nil, - completion: DataStoreCallback) { - delete(untypedModelType: modelType, - modelSchema: modelType.schema, - withIdentifier: identifier, - condition: condition, - completion: completion) + func delete( + untypedModelType modelType: Model.Type, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate? = nil, + completion: DataStoreCallback + ) { + delete( + untypedModelType: modelType, + modelSchema: modelType.schema, + withIdentifier: identifier, + condition: condition, + completion: completion + ) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineBehavior.swift index 43c8878703..9e02fe9fbb 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineBehavior.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import Combine +import Foundation enum StorageEngineEvent { case started diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift index 6e6781716a..1c1d0ed003 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift @@ -45,8 +45,10 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr var request: ObserveQueryRequest var context = InternalTaskAsyncThrowingSequenceContext>() - private let serialQueue = DispatchQueue(label: "com.amazonaws.AWSDataStoreObseverQueryOperation.serialQueue", - target: DispatchQueue.global()) + private let serialQueue = DispatchQueue( + label: "com.amazonaws.AWSDataStoreObseverQueryOperation.serialQueue", + target: DispatchQueue.global() + ) private let itemsChangedPeriodicPublishTimeInSeconds: DispatchQueue.SchedulerTimeType.Stride = 2 let modelType: M.Type @@ -74,17 +76,19 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr var dataStoreStatePublisher: AnyPublisher var dataStoreStateSink: AnyCancellable? - init(request: ObserveQueryRequest = .init(options: []), - context: InternalTaskAsyncThrowingSequenceContext> = InternalTaskAsyncThrowingSequenceContext>(), - modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate?, - sortInput: [QuerySortDescriptor]?, - storageEngine: StorageEngineBehavior, - dataStorePublisher: ModelSubcriptionBehavior, - dataStoreConfiguration: DataStoreConfiguration, - dispatchedModelSyncedEvent: AtomicValue, - dataStoreStatePublisher: AnyPublisher) { + init( + request: ObserveQueryRequest = .init(options: []), + context: InternalTaskAsyncThrowingSequenceContext> = InternalTaskAsyncThrowingSequenceContext>(), + modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate?, + sortInput: [QuerySortDescriptor]?, + storageEngine: StorageEngineBehavior, + dataStorePublisher: ModelSubcriptionBehavior, + dataStoreConfiguration: DataStoreConfiguration, + dispatchedModelSyncedEvent: AtomicValue, + dataStoreStatePublisher: AnyPublisher + ) { self.request = request self.context = context @@ -113,9 +117,9 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr func subscribeToDataStoreState() { serialQueue.async { [weak self] in - guard let self = self else { return } + guard let self else { return } - self.dataStoreStateSink = self.dataStoreStatePublisher.sink { completion in + dataStoreStateSink = dataStoreStatePublisher.sink { completion in switch completion { case .finished: self.finish() @@ -136,15 +140,15 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr public func cancel() { serialQueue.sync { - if let itemsChangedSink = itemsChangedSink { + if let itemsChangedSink { itemsChangedSink.cancel() } - if let batchItemsChangedSink = batchItemsChangedSink { + if let batchItemsChangedSink { batchItemsChangedSink.cancel() } - if let modelSyncedEventSink = modelSyncedEventSink { + if let modelSyncedEventSink { modelSyncedEventSink.cancel() } } @@ -178,7 +182,7 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr self.observeQueryStarted = true } - if let storageEngine = storageEngine { + if let storageEngine { self.storageEngine = storageEngine } self.log.verbose("Start ObserveQuery") @@ -208,7 +212,8 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr fail(error) return } - }) + } + ) } // MARK: Observe item changes @@ -221,36 +226,40 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr /// accessed under the serial queue. func subscribeToItemChanges() { serialQueue.async { [weak self] in - guard let self = self else { return } + guard let self else { return } - self.batchItemsChangedSink = self.dataStorePublisher.publisher + batchItemsChangedSink = dataStorePublisher.publisher .filter { _ in !self.dispatchedModelSyncedEvent.get() } - .filter(self.filterByModelName(mutationEvent:)) - .filter(self.filterByPredicateMatch(mutationEvent:)) - .handleEvents(receiveOutput: self.onItemChangeDuringSync(mutationEvent:) ) + .filter(filterByModelName(mutationEvent:)) + .filter(filterByPredicateMatch(mutationEvent:)) + .handleEvents(receiveOutput: onItemChangeDuringSync(mutationEvent:) ) .collect( .byTimeOrCount( // on queue - self.serialQueue, + serialQueue, // collect over this timeframe - self.itemsChangedPeriodicPublishTimeInSeconds, + itemsChangedPeriodicPublishTimeInSeconds, // If the `storageEngine` does sync from remote, the initial batch should // collect snapshots based on time / snapshots received. // If it doesn't, it should publish each snapshot without waiting. - self.storageEngine.syncsFromRemote - ? self.itemsChangedMaxSize + storageEngine.syncsFromRemote + ? itemsChangedMaxSize : 1 ) ) - .sink(receiveCompletion: self.onReceiveCompletion(completed:), - receiveValue: self.onItemsChangeDuringSync(mutationEvents:)) + .sink( + receiveCompletion: onReceiveCompletion(completed:), + receiveValue: onItemsChangeDuringSync(mutationEvents:) + ) - self.itemsChangedSink = self.dataStorePublisher.publisher + itemsChangedSink = dataStorePublisher.publisher .filter { _ in self.dispatchedModelSyncedEvent.get() } - .filter(self.filterByModelName(mutationEvent:)) - .receive(on: self.serialQueue) - .sink(receiveCompletion: self.onReceiveCompletion(completed:), - receiveValue: self.onItemChangeAfterSync(mutationEvent:)) + .filter(filterByModelName(mutationEvent:)) + .receive(on: serialQueue) + .sink( + receiveCompletion: onReceiveCompletion(completed:), + receiveValue: onItemChangeAfterSync(mutationEvent:) + ) } } @@ -273,7 +282,7 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr func filterByPredicateMatch(mutationEvent: MutationEvent) -> Bool { // Filter in the model when there is no predicate to check against. - guard let predicate = self.predicate else { + guard let predicate else { return true } do { @@ -288,24 +297,24 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr func onItemChangeDuringSync(mutationEvent: MutationEvent) { serialQueue.async { [weak self] in - guard let self = self, self.observeQueryStarted else { + guard let self, observeQueryStarted else { return } - self.apply(itemsChanged: [mutationEvent]) + apply(itemsChanged: [mutationEvent]) } } func onItemsChangeDuringSync(mutationEvents: [MutationEvent]) { serialQueue.async { [weak self] in - guard let self = self, - self.observeQueryStarted, + guard let self, + observeQueryStarted, !mutationEvents.isEmpty, !self.dispatchedModelSyncedEvent.get() else { return } - self.startSnapshotStopWatch() - self.sendSnapshot() + startSnapshotStopWatch() + sendSnapshot() } } @@ -393,12 +402,12 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr private func onReceiveCompletion(completed: Subscribers.Completion) { serialQueue.async { [weak self] in - guard let self = self else { return } + guard let self else { return } switch completed { case .finished: - self.finish() + finish() case .failure(let error): - self.fail(error) + fail(error) } } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift index 755a105f91..1cbba21d8d 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift @@ -37,7 +37,7 @@ class ObserveTaskRunner: InternalTaskRunner, InternalTaskAsyncThrowingSequence, guard !running else { return } running = true - self.sink = publisher.sink { completion in + sink = publisher.sink { completion in switch completion { case .finished: self.finish() diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift index b9eed6bbd9..054d807eb6 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift @@ -84,9 +84,11 @@ extension ModelSchema { /// - sortBy: The field and direction used to compare the two models /// - Returns: The resulting comparison between the two models based on `sortBy` // swiftlint:disable:next cyclomatic_complexity - func comparator(model1: Model, - model2: Model, - sortBy: QuerySortDescriptor) -> Bool? { + func comparator( + model1: Model, + model2: Model, + sortBy: QuerySortDescriptor + ) -> Bool? { let fieldName = sortBy.fieldName let sortOrder = sortBy.order guard let modelField = field(withName: fieldName) else { @@ -99,19 +101,25 @@ extension ModelSchema { guard let value1Optional = value1 as? String?, let value2Optional = value2 as? String? else { return false } - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) case .int, .timestamp: if let value1Optional = value1 as? Int?, let value2Optional = value2 as? Int? { - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) } if let value1Optional = value1 as? Int64?, let value2Optional = value2 as? Int64? { - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) } @@ -120,44 +128,56 @@ extension ModelSchema { guard let value1Optional = value1 as? Double?, let value2Optional = value2 as? Double? else { return false } - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) case .date: guard let value1Optional = value1 as? Temporal.Date?, let value2Optional = value2 as? Temporal.Date? else { return false } - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) case .dateTime: guard let value1Optional = value1 as? Temporal.DateTime?, let value2Optional = value2 as? Temporal.DateTime? else { return false } - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) case .time: guard let value1Optional = value1 as? Temporal.Time?, let value2Optional = value2 as? Temporal.Time? else { return false } - return ModelValueCompare(value1Optional: value1Optional, - value2Optional: value2Optional) + return ModelValueCompare( + value1Optional: value1Optional, + value2Optional: value2Optional + ) .sortComparator(sortOrder: sortOrder) case .bool: guard let value1Optional = value1 as? Bool?, let value2Optional = value2 as? Bool? else { return false } - return ModelValueCompare(value1Optional: value1Optional?.intValue, - value2Optional: value2Optional?.intValue) + return ModelValueCompare( + value1Optional: value1Optional?.intValue, + value2Optional: value2Optional?.intValue + ) .sortComparator(sortOrder: sortOrder) case .enum: + // swiftformat:disable typeSugar // swiftlint:disable syntactic_sugar guard case .some(Optional.some(let value1Optional)) = value1, - case .some(Optional.some(let value2Optional)) = value2 else { + case .some(Optional.some(let value2Optional)) = value2 + else { if value1 == nil && value2 != nil { return sortOrder == .ascending } else if value1 != nil && value2 == nil { @@ -166,10 +186,13 @@ extension ModelSchema { return false } // swiftlint:enable syntactic_sugar + // swiftformat:enable typeSugar let enumValue1Optional = (value1Optional as? EnumPersistable)?.rawValue let enumValue2Optional = (value2Optional as? EnumPersistable)?.rawValue - return ModelValueCompare(value1Optional: enumValue1Optional, - value2Optional: enumValue2Optional) + return ModelValueCompare( + value1Optional: enumValue1Optional, + value2Optional: enumValue2Optional + ) .sortComparator(sortOrder: sortOrder) case .embedded, .embeddedCollection, .model, .collection: // Behavior is undetermined diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/SortedList.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/SortedList.swift index daffa031a9..e0b2c960dc 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/SortedList.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/SortedList.swift @@ -61,7 +61,7 @@ class SortedList { func add(model: ModelType, sortInputs: [QuerySortDescriptor]) { let index = sortedModels.binarySearch { existingModel in var sortOrder: Bool? - var sortIndex: Int = 0 + var sortIndex = 0 while sortOrder == nil && sortIndex < sortInputs.endIndex { let sortInput = sortInputs[sortIndex] // `existingModel` is passed as left argument so the binarySearch's `predicate` criteria is met, ie. diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/ModelSyncedEvent.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/ModelSyncedEvent.swift index 15920e60d8..cbe94edc95 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/ModelSyncedEvent.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/ModelSyncedEvent.swift @@ -22,12 +22,14 @@ public struct ModelSyncedEvent { /// Number of existing model instances deleted from the local store public let deleted: Int - public init(modelName: String, - isFullSync: Bool, - isDeltaSync: Bool, - added: Int, - updated: Int, - deleted: Int) { + public init( + modelName: String, + isFullSync: Bool, + isDeltaSync: Bool, + added: Int, + updated: Int, + deleted: Int + ) { self.modelName = modelName self.isFullSync = isFullSync self.isDeltaSync = isDeltaSync diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/OutboxMutationEvent.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/OutboxMutationEvent.swift index 3fdf36b4d7..fa38a2b84c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/OutboxMutationEvent.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Events/OutboxMutationEvent.swift @@ -17,18 +17,24 @@ public struct OutboxMutationEvent { self.modelName = modelName self.element = element } - public static func fromModelWithMetadata(modelName: String, - model: Model, - mutationSync: MutationSync) -> OutboxMutationEvent { - let element = OutboxMutationEventElement(model: model, - version: mutationSync.syncMetadata.version, - lastChangedAt: mutationSync.syncMetadata.lastChangedAt, - deleted: mutationSync.syncMetadata.deleted) + public static func fromModelWithMetadata( + modelName: String, + model: Model, + mutationSync: MutationSync + ) -> OutboxMutationEvent { + let element = OutboxMutationEventElement( + model: model, + version: mutationSync.syncMetadata.version, + lastChangedAt: mutationSync.syncMetadata.lastChangedAt, + deleted: mutationSync.syncMetadata.deleted + ) return OutboxMutationEvent(modelName: modelName, element: element) } - public static func fromModelWithoutMetadata(modelName: String, - model: Model) -> OutboxMutationEvent { + public static func fromModelWithoutMetadata( + modelName: String, + model: Model + ) -> OutboxMutationEvent { let element = OutboxMutationEventElement(model: model) return OutboxMutationEvent(modelName: modelName, element: element) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift index b37a860eae..cbff57e91a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift @@ -38,7 +38,7 @@ final class InitialSyncOperation: AsynchronousOperation { } private var syncPredicateString: String? { - guard let syncPredicate = syncPredicate, + guard let syncPredicate, let data = try? syncPredicateEncoder.encode(syncPredicate) else { return nil } @@ -61,12 +61,14 @@ final class InitialSyncOperation: AsynchronousOperation { return initialSyncOperationTopic.eraseToAnyPublisher() } - init(modelSchema: ModelSchema, - api: APICategoryGraphQLBehavior?, - reconciliationQueue: IncomingEventReconciliationQueue?, - storageAdapter: StorageEngineAdapter?, - dataStoreConfiguration: DataStoreConfiguration, - authModeStrategy: AuthModeStrategy) { + init( + modelSchema: ModelSchema, + api: APICategoryGraphQLBehavior?, + reconciliationQueue: IncomingEventReconciliationQueue?, + storageAdapter: StorageEngineAdapter?, + dataStoreConfiguration: DataStoreConfiguration, + authModeStrategy: AuthModeStrategy + ) { self.modelSchema = modelSchema self.api = api self.reconciliationQueue = reconciliationQueue @@ -87,7 +89,7 @@ final class InitialSyncOperation: AsynchronousOperation { log.info("Beginning sync for \(modelSchema.name)") let lastSyncMetadata = getLastSyncMetadata() let lastSyncTime = getLastSyncTime(lastSyncMetadata) - self.queryTask = Task { + queryTask = Task { await query(lastSyncTime: lastSyncTime) } } @@ -98,7 +100,7 @@ final class InitialSyncOperation: AsynchronousOperation { return nil } - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { log.error(error: DataStoreError.nilStorageAdapter()) return nil } @@ -119,7 +121,7 @@ final class InitialSyncOperation: AsynchronousOperation { func getLastSyncTime(_ lastSyncMetadata: ModelSyncMetadata?) -> Int64? { let syncType: SyncType let lastSyncTime: Int64? - if syncPredicateChanged(self.syncPredicateString, lastSyncMetadata?.syncPredicate) { + if syncPredicateChanged(syncPredicateString, lastSyncMetadata?.syncPredicate) { log.info("SyncPredicate for \(modelSchema.name) changed, performing full sync.") lastSyncTime = nil syncType = .fullSync @@ -143,7 +145,7 @@ final class InitialSyncOperation: AsynchronousOperation { } private func getLastSyncTime(lastSync: Int64?) -> Int64? { - guard let lastSync = lastSync else { + guard let lastSync else { return nil } let lastSyncDate = Date(timeIntervalSince1970: TimeInterval.milliseconds(Double(lastSync))) @@ -163,7 +165,7 @@ final class InitialSyncOperation: AsynchronousOperation { return } - guard let api = api else { + guard let api else { finish(result: .failure(DataStoreError.nilAPIHandle())) return } @@ -172,7 +174,7 @@ final class InitialSyncOperation: AsynchronousOperation { let authTypes = await authModeStrategy.authTypesFor(schema: modelSchema, operation: .read) let queryRequestsStream = AsyncStream { continuation in for authType in authTypes { - continuation.yield({ [weak self] in + continuation.yield { [weak self] in guard let self, let api = self.api else { throw APIError.operationError( "The initial synchronization process can no longer be accessed or referred to", @@ -181,14 +183,14 @@ final class InitialSyncOperation: AsynchronousOperation { } return try await api.query(request: GraphQLRequest.syncQuery( - modelSchema: self.modelSchema, - where: self.syncPredicate, + modelSchema: modelSchema, + where: syncPredicate, limit: limit, nextToken: nextToken, lastSync: lastSyncTime, authType: authType.awsAuthType )) - }) + } } continuation.finish() } @@ -196,11 +198,11 @@ final class InitialSyncOperation: AsynchronousOperation { case .success(let graphQLResult): await handleQueryResults(lastSyncTime: lastSyncTime, graphQLResult: graphQLResult) case .failure(let apiError): - if self.isAuthSignedOutError(apiError: apiError) { - self.log.error("Sync for \(self.modelSchema.name) failed due to signed out error \(apiError.errorDescription)") + if isAuthSignedOutError(apiError: apiError) { + log.error("Sync for \(modelSchema.name) failed due to signed out error \(apiError.errorDescription)") } - self.dataStoreConfiguration.errorHandler(DataStoreError.api(apiError)) - self.finish(result: .failure(.api(apiError))) + dataStoreConfiguration.errorHandler(DataStoreError.api(apiError)) + finish(result: .failure(.api(apiError))) } } @@ -215,7 +217,7 @@ final class InitialSyncOperation: AsynchronousOperation { return } - guard let reconciliationQueue = reconciliationQueue else { + guard let reconciliationQueue else { finish(result: .failure(DataStoreError.nilReconciliationQueue())) return } @@ -244,7 +246,7 @@ final class InitialSyncOperation: AsynchronousOperation { } if let nextToken = syncQueryResult.nextToken, recordsReceived < syncMaxRecords { - await self.query(lastSyncTime: lastSyncTime, nextToken: nextToken) + await query(lastSyncTime: lastSyncTime, nextToken: nextToken) } else { updateModelSyncMetadata(lastSyncTime: syncQueryResult.startedAt) } @@ -256,14 +258,16 @@ final class InitialSyncOperation: AsynchronousOperation { return } - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { finish(result: .failure(DataStoreError.nilStorageAdapter())) return } - let syncMetadata = ModelSyncMetadata(id: modelSchema.name, - lastSync: lastSyncTime, - syncPredicate: syncPredicateString) + let syncMetadata = ModelSyncMetadata( + id: modelSchema.name, + lastSync: lastSyncTime, + syncPredicate: syncPredicateString + ) storageAdapter.save(syncMetadata, condition: nil, eagerLoad: true) { result in switch result { case .failure(let dataStoreError): @@ -297,7 +301,7 @@ final class InitialSyncOperation: AsynchronousOperation { } override func cancel() { - self.queryTask?.cancel() + queryTask?.cancel() } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift index 806b19a240..2e54102e8e 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift @@ -17,11 +17,13 @@ protocol InitialSyncOrchestrator { // For testing typealias InitialSyncOrchestratorFactory = - (DataStoreConfiguration, - AuthModeStrategy, - APICategoryGraphQLBehavior?, - IncomingEventReconciliationQueue?, - StorageEngineAdapter?) -> InitialSyncOrchestrator + ( + DataStoreConfiguration, + AuthModeStrategy, + APICategoryGraphQLBehavior?, + IncomingEventReconciliationQueue?, + StorageEngineAdapter? + ) -> InitialSyncOrchestrator final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { typealias SyncOperationResult = Result @@ -42,19 +44,23 @@ final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { // Future optimization: can perform sync on each root in parallel, since we know they won't have any // interdependencies let syncOperationQueue: OperationQueue - private let concurrencyQueue = DispatchQueue(label: "com.amazonaws.InitialSyncOrchestrator.concurrencyQueue", - target: DispatchQueue.global()) + private let concurrencyQueue = DispatchQueue( + label: "com.amazonaws.InitialSyncOrchestrator.concurrencyQueue", + target: DispatchQueue.global() + ) private let initialSyncOrchestratorTopic: PassthroughSubject var publisher: AnyPublisher { return initialSyncOrchestratorTopic.eraseToAnyPublisher() } - init(dataStoreConfiguration: DataStoreConfiguration, - authModeStrategy: AuthModeStrategy, - api: APICategoryGraphQLBehavior?, - reconciliationQueue: IncomingEventReconciliationQueue?, - storageAdapter: StorageEngineAdapter?) { + init( + dataStoreConfiguration: DataStoreConfiguration, + authModeStrategy: AuthModeStrategy, + api: APICategoryGraphQLBehavior?, + reconciliationQueue: IncomingEventReconciliationQueue?, + storageAdapter: StorageEngineAdapter? + ) { self.initialSyncOperationSinks = [:] self.dataStoreConfiguration = dataStoreConfiguration self.authModeStrategy = authModeStrategy @@ -81,10 +87,10 @@ final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { self.log.info("Beginning initial sync") - let syncableModelSchemas = ModelRegistry.modelSchemas.filter { $0.isSyncable } + let syncableModelSchemas = ModelRegistry.modelSchemas.filter(\.isSyncable) self.enqueueSyncableModels(syncableModelSchemas) - let modelNames = syncableModelSchemas.map { $0.name } + let modelNames = syncableModelSchemas.map(\.name) self.dispatchSyncQueriesStarted(for: modelNames) if !syncableModelSchemas.hasAssociations() { self.syncOperationQueue.maxConcurrentOperationCount = syncableModelSchemas.count @@ -102,19 +108,25 @@ final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { /// Enqueues sync operations for models and downstream dependencies private func enqueueSyncOperation(for modelSchema: ModelSchema) { - let initialSyncForModel = InitialSyncOperation(modelSchema: modelSchema, - api: api, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter, - dataStoreConfiguration: dataStoreConfiguration, - authModeStrategy: authModeStrategy) + let initialSyncForModel = InitialSyncOperation( + modelSchema: modelSchema, + api: api, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter, + dataStoreConfiguration: dataStoreConfiguration, + authModeStrategy: authModeStrategy + ) initialSyncOperationSinks[modelSchema.name] = initialSyncForModel .publisher .receive(on: concurrencyQueue) - .sink(receiveCompletion: { result in self.onReceiveCompletion(modelSchema: modelSchema, - result: result) }, - receiveValue: onReceiveValue(_:)) + .sink( + receiveCompletion: { result in self.onReceiveCompletion( + modelSchema: modelSchema, + result: result + ) }, + receiveValue: onReceiveValue(_:) + ) syncOperationQueue.addOperation(initialSyncForModel) } @@ -128,8 +140,9 @@ final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { let syncError = DataStoreError.sync( "An error occurred syncing \(modelSchema.name)", "", - dataStoreError) - self.syncErrors.append(syncError) + dataStoreError + ) + syncErrors.append(syncError) } initialSyncOperationSinks.removeValue(forKey: modelSchema.name) @@ -170,8 +183,10 @@ final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { private func dispatchSyncQueriesStarted(for modelNames: [String]) { let syncQueriesStartedEvent = SyncQueriesStartedEvent(models: modelNames) - let syncQueriesStartedEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.syncQueriesStarted, - data: syncQueriesStartedEvent) + let syncQueriesStartedEventPayload = HubPayload( + eventName: HubPayload.EventName.DataStore.syncQueriesStarted, + data: syncQueriesStartedEvent + ) log.verbose("[Lifecycle event 2]: syncQueriesStarted") Amplify.Hub.dispatch(to: .dataStore, payload: syncQueriesStartedEventPayload) } @@ -251,8 +266,10 @@ extension AWSInitialSyncOrchestrator { if case let .api(amplifyError, _) = datastoreError, let apiError = amplifyError as? APIError { if case .operationError(let errorDescription, _, _) = apiError, - errorDescription.range(of: "Unauthorized", - options: .caseInsensitive) != nil { + errorDescription.range( + of: "Unauthorized", + options: .caseInsensitive + ) != nil { return true } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ModelSyncedEventEmitter.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ModelSyncedEventEmitter.swift index 8e59168d0d..2fbe12e66e 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ModelSyncedEventEmitter.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ModelSyncedEventEmitter.swift @@ -25,8 +25,10 @@ enum IncomingModelSyncedEmitterEvent { /// - Check if it `ModelSyncedEvent` should be emitted, if so, emit it. /// - Then send the mutation event which was used in the check above. final class ModelSyncedEventEmitter { - private let queue = DispatchQueue(label: "com.amazonaws.ModelSyncedEventEmitterQueue", - target: DispatchQueue.global()) + private let queue = DispatchQueue( + label: "com.amazonaws.ModelSyncedEventEmitterQueue", + target: DispatchQueue.global() + ) private var syncOrchestratorSink: AnyCancellable? private var reconciliationQueueSink: AnyCancellable? @@ -50,9 +52,11 @@ final class ModelSyncedEventEmitter { /// Used within ModelSyncedEventEmitter instances, not thread-safe, is accessed serially under DispatchQueue. var dispatchedModelSyncedEvent: Bool - init(modelSchema: ModelSchema, - initialSyncOrchestrator: InitialSyncOrchestrator?, - reconciliationQueue: IncomingEventReconciliationQueue?) { + init( + modelSchema: ModelSchema, + initialSyncOrchestrator: InitialSyncOrchestrator?, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { self.modelSchema = modelSchema self.recordsReceived = 0 self.reconciledReceived = 0 @@ -66,19 +70,23 @@ final class ModelSyncedEventEmitter { .publisher .receive(on: queue) .filter { [weak self] in self?.filterSyncOperationEvent($0) == true } - .sink(receiveCompletion: { _ in }, - receiveValue: { [weak self] value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { [weak self] value in self?.onReceiveSyncOperationEvent(value: value) - }) + } + ) self.reconciliationQueueSink = reconciliationQueue? .publisher .receive(on: queue) .filter { [weak self] in self?.filterReconciliationQueueEvent($0) == true } - .sink(receiveCompletion: { _ in }, - receiveValue: { [weak self] value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { [weak self] value in self?.onReceiveReconciliationEvent(value: value) - }) + } + ) } /// Filtering `InitialSyncOperationEvent`s that come from `InitialSyncOperation` of the same ModelType diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ReadyEventEmitter.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ReadyEventEmitter.swift index 66f73bf9ba..3a06731e85 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ReadyEventEmitter.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/ReadyEventEmitter.swift @@ -28,7 +28,7 @@ final class ReadyEventEmitter { let syncEngineStartedPublisher = ReadyEventEmitter.makeRemoteSyncEngineStartedPublisher( remoteSyncEnginePublisher: remoteSyncEnginePublisher ) - readySink = Publishers + self.readySink = Publishers .Merge(queriesReadyPublisher, syncEngineStartedPublisher) .sink(receiveCompletion: { completion in switch completion { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/SyncEventEmitter.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/SyncEventEmitter.swift index 789849aa1e..9b9e51d207 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/SyncEventEmitter.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/SyncEventEmitter.swift @@ -21,8 +21,10 @@ enum IncomingSyncEventEmitterEvent { /// emit the `syncQueriesReady` and sends back the reconciliation events (`.mutationEventApplied`, /// `.mutationEventDropped`) to its subscribers. final class SyncEventEmitter { - private let queue = DispatchQueue(label: "com.amazonaws.SyncEventEmitter", - target: DispatchQueue.global()) + private let queue = DispatchQueue( + label: "com.amazonaws.SyncEventEmitter", + target: DispatchQueue.global() + ) var modelSyncedEventEmitters: [String: ModelSyncedEventEmitter] var initialSyncCompleted: AnyCancellable? @@ -39,20 +41,24 @@ final class SyncEventEmitter { syncableModels == modelSyncedReceived } - init(initialSyncOrchestrator: InitialSyncOrchestrator?, - reconciliationQueue: IncomingEventReconciliationQueue?) { + init( + initialSyncOrchestrator: InitialSyncOrchestrator?, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { self.modelSyncedEventEmitters = [String: ModelSyncedEventEmitter]() self.syncEventEmitterTopic = PassthroughSubject() self.modelSyncedReceived = 0 - let syncableModelSchemas = ModelRegistry.modelSchemas.filter { $0.isSyncable } + let syncableModelSchemas = ModelRegistry.modelSchemas.filter(\.isSyncable) self.syncableModels = syncableModelSchemas.count var publishers = [AnyPublisher]() for syncableModelSchema in syncableModelSchemas { - let modelSyncedEventEmitter = ModelSyncedEventEmitter(modelSchema: syncableModelSchema, - initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + let modelSyncedEventEmitter = ModelSyncedEventEmitter( + modelSchema: syncableModelSchema, + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) modelSyncedEventEmitters[syncableModelSchema.name] = modelSyncedEventEmitter publishers.append(modelSyncedEventEmitter.publisher) } @@ -60,10 +66,12 @@ final class SyncEventEmitter { self.initialSyncCompleted = Publishers .MergeMany(publishers) .receive(on: queue) - .sink(receiveCompletion: { _ in }, - receiveValue: { [weak self] value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { [weak self] value in self?.onReceiveModelSyncedEmitterEvent(value: value) - }) + } + ) } private func onReceiveModelSyncedEmitterEvent(value: IncomingModelSyncedEmitterEvent) { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift index 3a419c8d78..e96e905131 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift @@ -22,37 +22,48 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { return } - self.resolveConflictsThenSave(mutationEvent: mutationEvent, - storageAdapter: storageAdapter, - completion: completion) + self.resolveConflictsThenSave( + mutationEvent: mutationEvent, + storageAdapter: storageAdapter, + completion: completion + ) } } /// Resolves conflicts for the offered mutationEvent, and either accepts the event, returning a disposition, or /// rejects the event with an error - func resolveConflictsThenSave(mutationEvent: MutationEvent, - storageAdapter: StorageEngineAdapter, - completion: @escaping (Result) -> Void) { + func resolveConflictsThenSave( + mutationEvent: MutationEvent, + storageAdapter: StorageEngineAdapter, + completion: @escaping (Result) -> Void + ) { MutationEvent.pendingMutationEvents( forMutationEvent: mutationEvent, - storageAdapter: storageAdapter) { result in + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let dataStoreError): completion(.failure(dataStoreError)) case .success(let localMutationEvents): - let mutationDisposition = self.disposition(for: mutationEvent, - given: localMutationEvents) - self.resolve(candidate: mutationEvent, - localEvents: localMutationEvents, - per: mutationDisposition, - storageAdapter: storageAdapter, - completionPromise: completion) + let mutationDisposition = self.disposition( + for: mutationEvent, + given: localMutationEvents + ) + self.resolve( + candidate: mutationEvent, + localEvents: localMutationEvents, + per: mutationDisposition, + storageAdapter: storageAdapter, + completionPromise: completion + ) } } } - func disposition(for candidate: MutationEvent, - given localEvents: [MutationEvent]) -> MutationDisposition { + func disposition( + for candidate: MutationEvent, + given localEvents: [MutationEvent] + ) -> MutationDisposition { guard !localEvents.isEmpty, let existingEvent = localEvents.first else { log.verbose("\(#function) no local events, saving candidate") @@ -65,15 +76,19 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { guard let candidateMutationType = GraphQLMutationType(rawValue: candidate.mutationType) else { let dataStoreError = - DataStoreError.unknown("Couldn't get mutation type for \(candidate.mutationType)", - AmplifyErrorMessages.shouldNotHappenReportBugToAWS()) + DataStoreError.unknown( + "Couldn't get mutation type for \(candidate.mutationType)", + AmplifyErrorMessages.shouldNotHappenReportBugToAWS() + ) return .dropCandidateWithError(dataStoreError) } guard let existingMutationType = GraphQLMutationType(rawValue: existingEvent.mutationType) else { let dataStoreError = - DataStoreError.unknown("Couldn't get mutation type for \(existingEvent.mutationType)", - AmplifyErrorMessages.shouldNotHappenReportBugToAWS()) + DataStoreError.unknown( + "Couldn't get mutation type for \(existingEvent.mutationType)", + AmplifyErrorMessages.shouldNotHappenReportBugToAWS() + ) return .dropCandidateWithError(dataStoreError) } @@ -98,7 +113,7 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { model. Candidate model is below: \(candidate) """ - ) + ) return .dropCandidateWithError(dataStoreError) case (.delete, .update): @@ -110,17 +125,19 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { model. Candidate model is below: \(candidate) """ - ) + ) return .dropCandidateWithError(dataStoreError) } } - func resolve(candidate: MutationEvent, - localEvents: [MutationEvent], - per disposition: MutationDisposition, - storageAdapter: StorageEngineAdapter, - completionPromise: @escaping Future.Promise) { + func resolve( + candidate: MutationEvent, + localEvents: [MutationEvent], + per disposition: MutationDisposition, + storageAdapter: StorageEngineAdapter, + completionPromise: @escaping Future.Promise + ) { log.verbose("\(#function) disposition \(disposition)") switch disposition { @@ -133,10 +150,12 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { for localEvent in localEvents { group.addTask { try await withCheckedThrowingContinuation { continuation in - storageAdapter.delete(untypedModelType: MutationEvent.self, - modelSchema: MutationEvent.schema, - withIdentifier: localEvent.identifier(schema: MutationEvent.schema), - condition: nil) { result in + storageAdapter.delete( + untypedModelType: MutationEvent.self, + modelSchema: MutationEvent.schema, + withIdentifier: localEvent.identifier(schema: MutationEvent.schema), + condition: nil + ) { result in continuation.resume(with: result) } } @@ -150,15 +169,19 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { } } case .saveCandidate: - save(mutationEvent: candidate, - storageAdapter: storageAdapter, - completionPromise: completionPromise) + save( + mutationEvent: candidate, + storageAdapter: storageAdapter, + completionPromise: completionPromise + ) case .replaceLocalWithCandidate: guard !localEvents.isEmpty, let eventToUpdate = localEvents.first else { // Should be caught upstream, but being defensive - save(mutationEvent: candidate, - storageAdapter: storageAdapter, - completionPromise: completionPromise) + save( + mutationEvent: candidate, + storageAdapter: storageAdapter, + completionPromise: completionPromise + ) return } @@ -166,30 +189,35 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { // TODO: Handle errors from delete localEvents .suffix(from: 1) - .forEach { storageAdapter.delete(MutationEvent.self, - modelSchema: MutationEvent.schema, - withIdentifier: $0.identifier(schema: MutationEvent.schema), - condition: nil) { _ in } } + .forEach { storageAdapter.delete( + MutationEvent.self, + modelSchema: MutationEvent.schema, + withIdentifier: $0.identifier(schema: MutationEvent.schema), + condition: nil + ) { _ in } } } let resolvedEvent = getResolvedEvent(for: eventToUpdate, applying: candidate) - save(mutationEvent: resolvedEvent, - storageAdapter: storageAdapter, - completionPromise: completionPromise) + save( + mutationEvent: resolvedEvent, + storageAdapter: storageAdapter, + completionPromise: completionPromise + ) } } - private func getResolvedEvent(for originalEvent: MutationEvent, - applying candidate: MutationEvent) -> MutationEvent { + private func getResolvedEvent( + for originalEvent: MutationEvent, + applying candidate: MutationEvent + ) -> MutationEvent { var resolvedEvent = originalEvent resolvedEvent.json = candidate.json - let updatedMutationType: String - if candidate.mutationType == GraphQLMutationType.delete.rawValue { - updatedMutationType = candidate.mutationType + let updatedMutationType: String = if candidate.mutationType == GraphQLMutationType.delete.rawValue { + candidate.mutationType } else { - updatedMutationType = originalEvent.mutationType + originalEvent.mutationType } resolvedEvent.mutationType = updatedMutationType @@ -204,7 +232,7 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { completionPromise: @escaping Future.Promise ) { log.verbose("\(#function) mutationEvent: \(mutationEvent)") - let nextEventPromise = self.nextEventPromise.getAndSet(nil) + let nextEventPromise = nextEventPromise.getAndSet(nil) var eventToPersist = mutationEvent if nextEventPromise != nil { eventToPersist.inProcess = true diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventSource.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventSource.swift index cdd83055a6..2e17e407e7 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventSource.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventSource.swift @@ -9,7 +9,7 @@ import Amplify import Combine extension AWSMutationDatabaseAdapter: MutationEventSource { - + /// DataStore implements a FIFO queue of MutationEvents by using the local database /// and querying for the earliest MutationEvent by its `createdAt` field. /// @@ -30,7 +30,7 @@ extension AWSMutationDatabaseAdapter: MutationEventSource { func getNextMutationEvent(completion: @escaping DataStoreCallback) { log.verbose(#function) - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { completion(.failure(DataStoreError.nilStorageAdapter())) return } @@ -40,7 +40,8 @@ extension AWSMutationDatabaseAdapter: MutationEventSource { predicate: nil, sort: [sort], paginationInput: nil, - eagerLoad: true) { result in + eagerLoad: true + ) { result in switch result { case .failure(let dataStoreError): completion(.failure(dataStoreError)) @@ -53,18 +54,22 @@ extension AWSMutationDatabaseAdapter: MutationEventSource { log.verbose("The head of the MutationEvent queue was already inProcess (most likely interrupted process): \(mutationEvent)") completion(.success(mutationEvent)) } else { - self.markInProcess(mutationEvent: mutationEvent, - storageAdapter: storageAdapter, - completion: completion) + self.markInProcess( + mutationEvent: mutationEvent, + storageAdapter: storageAdapter, + completion: completion + ) } } } } - func markInProcess(mutationEvent: MutationEvent, - storageAdapter: StorageEngineAdapter, - completion: @escaping DataStoreCallback) { + func markInProcess( + mutationEvent: MutationEvent, + storageAdapter: StorageEngineAdapter, + completion: @escaping DataStoreCallback + ) { var inProcessEvent = mutationEvent inProcessEvent.inProcess = true storageAdapter.save(inProcessEvent, condition: nil, eagerLoad: true, completion: completion) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/AWSMutationEventPublisher.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/AWSMutationEventPublisher.swift index 77fc9d16c7..d6cf0eca9a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/AWSMutationEventPublisher.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/AWSMutationEventPublisher.swift @@ -53,7 +53,7 @@ final class AWSMutationEventPublisher: Publisher { func requestNextEvent() { log.verbose(#function) let promise: DataStoreCallback = { [weak self] result in - guard let self = self, let subscriber = self.subscription?.subscriber else { + guard let self, let subscriber = subscription?.subscriber else { return } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventClearState.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventClearState.swift index 52b3f301fa..8dd1c6fc6a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventClearState.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventClearState.swift @@ -19,18 +19,22 @@ final class MutationEventClearState { let fields = MutationEvent.keys let predicate = fields.inProcess == true let sort = QuerySortDescriptor(fieldName: fields.createdAt.stringValue, order: .ascending) - storageAdapter.query(MutationEvent.self, - predicate: predicate, - sort: [sort], - paginationInput: nil, - eagerLoad: true) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate, + sort: [sort], + paginationInput: nil, + eagerLoad: true + ) { result in switch result { case .failure(let dataStoreError): log.error("Failed on clearStateOutgoingMutations: \(dataStoreError)") case .success(let mutationEvents): if !mutationEvents.isEmpty { - updateMutationsState(mutationEvents: mutationEvents, - completion: completion) + updateMutationsState( + mutationEvents: mutationEvents, + completion: completion + ) } else { completion() } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventSubscription.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventSubscription.swift index bd86169200..ae6d7e1460 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventSubscription.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventSubscription.swift @@ -14,8 +14,10 @@ final class MutationEventSubscription: Subscription { let subscriber: MutationEventSubscriber private weak var publisher: AWSMutationEventPublisher? - init(subscriber: S, - publisher: AWSMutationEventPublisher) where S: Subscriber, + init( + subscriber: S, + publisher: AWSMutationEventPublisher + ) where S: Subscriber, S.Failure == DataStoreError, S.Input == MutationEvent { self.subscriber = MutationEventSubscriber(subscriber: subscriber) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/MutationRetryNotifier.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/MutationRetryNotifier.swift index 6aa55c2671..92261021b8 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/MutationRetryNotifier.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/MutationRetryNotifier.swift @@ -6,9 +6,9 @@ // import Amplify -import Foundation import AWSPluginsCore import Combine +import Foundation final class MutationRetryNotifier { private var lock: NSLock @@ -17,9 +17,11 @@ final class MutationRetryNotifier { var retryMutationCallback: () -> Void private var reachabilitySubscription: Subscription? - init(advice: RequestRetryAdvice, - networkReachabilityPublisher: AnyPublisher?, - retryMutationCallback: @escaping BasicClosure) { + init( + advice: RequestRetryAdvice, + networkReachabilityPublisher: AnyPublisher?, + retryMutationCallback: @escaping BasicClosure + ) { self.lock = NSLock() self.retryMutationCallback = retryMutationCallback diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue+Resolver.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue+Resolver.swift index 2c066d214d..6490b2a85a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue+Resolver.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue+Resolver.swift @@ -10,7 +10,7 @@ import Combine extension OutgoingMutationQueue { - struct Resolver { + enum Resolver { static func resolve(currentState: State, action: Action) -> State { switch (currentState, action) { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift index e2840f7e47..5aa9085fae 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift @@ -6,16 +6,18 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore /// Submits outgoing mutation events to the provisioned API protocol OutgoingMutationQueueBehavior: AnyObject { func stopSyncingToCloud(_ completion: @escaping BasicClosure) - func startSyncingToCloud(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) + func startSyncingToCloud( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) var publisher: AnyPublisher { get } } @@ -42,10 +44,12 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { return outgoingMutationQueueSubject.eraseToAnyPublisher() } - init(_ stateMachine: StateMachine? = nil, - storageAdapter: StorageEngineAdapter, - dataStoreConfiguration: DataStoreConfiguration, - authModeStrategy: AuthModeStrategy) { + init( + _ stateMachine: StateMachine? = nil, + storageAdapter: StorageEngineAdapter, + dataStoreConfiguration: DataStoreConfiguration, + authModeStrategy: AuthModeStrategy + ) { self.storageAdapter = storageAdapter self.dataStoreConfiguration = dataStoreConfiguration self.authModeStrategy = authModeStrategy @@ -59,8 +63,10 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { self.operationQueue = operationQueue self.stateMachine = stateMachine ?? - StateMachine(initialState: .notInitialized, - resolver: OutgoingMutationQueue.Resolver.resolve(currentState:action:)) + StateMachine( + initialState: .notInitialized, + resolver: OutgoingMutationQueue.Resolver.resolve(currentState:action:) + ) self.outgoingMutationQueueSubject = PassthroughSubject() @@ -69,8 +75,8 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { .sink { [weak self] newState in guard let self else { return } - self.log.verbose("New state: \(newState)") - self.mutationDispatchQueue.async { + log.verbose("New state: \(newState)") + mutationDispatchQueue.async { self.respond(to: newState) } } @@ -81,9 +87,11 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { // MARK: - Public API - func startSyncingToCloud(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) { + func startSyncingToCloud( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { log.verbose(#function) stateMachine.notify(action: .receivedStart(api, mutationEventPublisher, reconciliationQueue)) } @@ -127,21 +135,23 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { /// Responder method for `starting`. Starts the operation queue and subscribes to /// the publisher. After subscribing to the publisher, return actions: /// - receivedSubscription - private func doStart(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) { + private func doStart( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { log.verbose(#function) self.api = api self.reconciliationQueue = reconciliationQueue queryMutationEventsFromStorage { [weak self] in - guard let self = self else { return } - guard case .starting = self.stateMachine.state else { - self.log.debug("Unexpected state transition while performing `doStart()` during `.starting` state. Current state: \(self.stateMachine.state).") + guard let self else { return } + guard case .starting = stateMachine.state else { + log.debug("Unexpected state transition while performing `doStart()` during `.starting` state. Current state: \(stateMachine.state).") return } - self.operationQueue.isSuspended = false + operationQueue.isSuspended = false // State machine notification to ".receivedSubscription" will be handled in `receive(subscription:)` mutationEventPublisher.publisher.subscribe(self) } @@ -153,7 +163,7 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { private func doStop(completion: @escaping BasicClosure) { log.verbose(#function) doStopWithoutNotifyingStateMachine() - self.stateMachine.notify(action: .doneStopping) + stateMachine.notify(action: .doneStopping) completion() } @@ -173,7 +183,7 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { /// - errored private func requestEvent() { log.verbose(#function) - guard let subscription = subscription else { + guard let subscription else { let dataStoreError = DataStoreError.unknown( "No subscription when requesting event", """ @@ -190,7 +200,7 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { /// Invoked when the subscription receives an event, not as part of the state machine transition private func enqueue(_ mutationEvent: MutationEvent) { log.verbose(#function) - guard let api = api else { + guard let api else { let dataStoreError = DataStoreError.configuration( "API is unexpectedly nil", """ @@ -221,33 +231,43 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { } } - private func processSyncMutationToCloudResult(_ result: GraphQLOperation>.OperationResult, - mutationEvent: MutationEvent, - api: APICategoryGraphQLBehavior) { + private func processSyncMutationToCloudResult( + _ result: GraphQLOperation>.OperationResult, + mutationEvent: MutationEvent, + api: APICategoryGraphQLBehavior + ) { if case let .success(graphQLResponse) = result { if case let .success(graphQLResult) = graphQLResponse { - processSuccessEvent(mutationEvent, - mutationSync: graphQLResult) + processSuccessEvent( + mutationEvent, + mutationSync: graphQLResult + ) } else if case let .failure(graphQLResponseError) = graphQLResponse { - processMutationErrorFromCloud(mutationEvent: mutationEvent, - api: api, - apiError: nil, - graphQLResponseError: graphQLResponseError) + processMutationErrorFromCloud( + mutationEvent: mutationEvent, + api: api, + apiError: nil, + graphQLResponseError: graphQLResponseError + ) } } else if case let .failure(apiError) = result { - processMutationErrorFromCloud(mutationEvent: mutationEvent, - api: api, - apiError: apiError, - graphQLResponseError: nil) + processMutationErrorFromCloud( + mutationEvent: mutationEvent, + api: api, + apiError: apiError, + graphQLResponseError: nil + ) } } /// Process the successful response from API by updating the mutation events in /// mutation event table having `nil` version - private func processSuccessEvent(_ mutationEvent: MutationEvent, - mutationSync: MutationSync?) { - if let mutationSync = mutationSync { - guard let reconciliationQueue = reconciliationQueue else { + private func processSuccessEvent( + _ mutationEvent: MutationEvent, + mutationSync: MutationSync? + ) { + if let mutationSync { + guard let reconciliationQueue else { let dataStoreError = DataStoreError.configuration( "reconciliationQueue is unexpectedly nil", """ @@ -271,11 +291,13 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { } } - private func processMutationErrorFromCloud(mutationEvent: MutationEvent, - api: APICategoryGraphQLBehavior, - apiError: APIError?, - graphQLResponseError: GraphQLResponseError>?) { - if let apiError = apiError, apiError.isOperationCancelledError { + private func processMutationErrorFromCloud( + mutationEvent: MutationEvent, + api: APICategoryGraphQLBehavior, + apiError: APIError?, + graphQLResponseError: GraphQLResponseError>? + ) { + if let apiError, apiError.isOperationCancelledError { log.verbose("SyncMutationToCloudOperation was cancelled, aborting processing") return } @@ -289,21 +311,23 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { apiError: apiError, reconciliationQueue: reconciliationQueue ) { [weak self] result in - guard let self = self else { + guard let self else { return } - self.log.verbose("[ProcessMutationErrorFromCloudOperation] result: \(result)") + log.verbose("[ProcessMutationErrorFromCloudOperation] result: \(result)") if case let .success(mutationEventOptional) = result, let outgoingMutationEvent = mutationEventOptional { - self.outgoingMutationQueueSubject.send(outgoingMutationEvent) + outgoingMutationQueueSubject.send(outgoingMutationEvent) } - self.completeProcessingEvent(mutationEvent) + completeProcessingEvent(mutationEvent) } operationQueue.addOperation(processMutationErrorFromCloudOperation) } - private func completeProcessingEvent(_ mutationEvent: MutationEvent, - mutationSync: MutationSync? = nil) { + private func completeProcessingEvent( + _ mutationEvent: MutationEvent, + mutationSync: MutationSync? = nil + ) { // TODO: We shouldn't be inspecting state, we should be using granular enough states to // ensure we don't encounter forbidden transitions. if case .stopped = stateMachine.state { @@ -319,13 +343,15 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { } catch { self.log.verbose("mutationEvent failed to delete: error: \(error)") } - if let mutationSync = mutationSync { - self.dispatchOutboxMutationProcessedEvent(mutationEvent: mutationEvent, - mutationSync: mutationSync) + if let mutationSync { + self.dispatchOutboxMutationProcessedEvent( + mutationEvent: mutationEvent, + mutationSync: mutationSync + ) } self.queryMutationEventsFromStorage { [weak self] in guard let self else { return } - self.stateMachine.notify(action: .processedEvent) + stateMachine.notify(action: .processedEvent) } } } @@ -334,16 +360,18 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { let fields = MutationEvent.keys let predicate = fields.inProcess == false || fields.inProcess == nil - storageAdapter.query(MutationEvent.self, - predicate: predicate, - sort: nil, - paginationInput: nil, - eagerLoad: true) { [weak self] result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate, + sort: nil, + paginationInput: nil, + eagerLoad: true + ) { [weak self] result in guard let self else { return } switch result { case .success(let events): - self.dispatchOutboxStatusEvent(isEmpty: events.isEmpty) + dispatchOutboxStatusEvent(isEmpty: events.isEmpty) case .failure(let error): log.error("Error querying mutation events: \(error)") } @@ -351,16 +379,22 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { } } - private func dispatchOutboxMutationProcessedEvent(mutationEvent: MutationEvent, - mutationSync: MutationSync) { + private func dispatchOutboxMutationProcessedEvent( + mutationEvent: MutationEvent, + mutationSync: MutationSync + ) { do { let localModel = try mutationEvent.decodeModel() let outboxMutationProcessedEvent = OutboxMutationEvent - .fromModelWithMetadata(modelName: mutationEvent.modelName, - model: localModel, - mutationSync: mutationSync) - let payload = HubPayload(eventName: HubPayload.EventName.DataStore.outboxMutationProcessed, - data: outboxMutationProcessedEvent) + .fromModelWithMetadata( + modelName: mutationEvent.modelName, + model: localModel, + mutationSync: mutationSync + ) + let payload = HubPayload( + eventName: HubPayload.EventName.DataStore.outboxMutationProcessed, + data: outboxMutationProcessedEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: payload) } catch { log.error("\(#function) Couldn't decode local model as \(mutationEvent.modelName) \(error)") @@ -373,10 +407,14 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { do { let localModel = try mutationEvent.decodeModel() let outboxMutationEnqueuedEvent = OutboxMutationEvent - .fromModelWithoutMetadata(modelName: mutationEvent.modelName, - model: localModel) - let payload = HubPayload(eventName: HubPayload.EventName.DataStore.outboxMutationEnqueued, - data: outboxMutationEnqueuedEvent) + .fromModelWithoutMetadata( + modelName: mutationEvent.modelName, + model: localModel + ) + let payload = HubPayload( + eventName: HubPayload.EventName.DataStore.outboxMutationEnqueued, + data: outboxMutationEnqueuedEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: payload) } catch { log.error("\(#function) Couldn't decode local model as \(mutationEvent.modelName) \(error)") @@ -387,8 +425,10 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { private func dispatchOutboxStatusEvent(isEmpty: Bool) { let outboxStatusEvent = OutboxStatusEvent(isEmpty: isEmpty) - let outboxStatusEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.outboxStatus, - data: outboxStatusEvent) + let outboxStatusEventPayload = HubPayload( + eventName: HubPayload.EventName.DataStore.outboxStatus, + data: outboxStatusEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: outboxStatusEventPayload) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift index c334745fb7..b3f2b89049 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore // swiftlint:disable type_body_length file_length /// Checks the GraphQL error response for specific error scenarios related to data synchronziation to the local store. @@ -30,14 +30,16 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { private weak var api: APICategoryGraphQLBehavior? private weak var reconciliationQueue: IncomingEventReconciliationQueue? - init(dataStoreConfiguration: DataStoreConfiguration, - mutationEvent: MutationEvent, - api: APICategoryGraphQLBehavior, - storageAdapter: StorageEngineAdapter, - graphQLResponseError: GraphQLResponseError>? = nil, - apiError: APIError? = nil, - reconciliationQueue: IncomingEventReconciliationQueue? = nil, - completion: @escaping (Result) -> Void) { + init( + dataStoreConfiguration: DataStoreConfiguration, + mutationEvent: MutationEvent, + api: APICategoryGraphQLBehavior, + storageAdapter: StorageEngineAdapter, + graphQLResponseError: GraphQLResponseError>? = nil, + apiError: APIError? = nil, + reconciliationQueue: IncomingEventReconciliationQueue? = nil, + completion: @escaping (Result) -> Void + ) { self.dataStoreConfiguration = dataStoreConfiguration self.mutationEvent = mutationEvent self.api = api @@ -58,7 +60,7 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { return } - if let apiError = apiError { + if let apiError { if isAuthSignedOutError(apiError: apiError) { log.verbose("User is signed out, passing error back to the error handler, and removing mutation event.") } else if let underlyingError = apiError.underlyingError { @@ -71,10 +73,12 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { return } - guard let graphQLResponseError = graphQLResponseError else { + guard let graphQLResponseError else { dataStoreConfiguration.errorHandler( - DataStoreError.api(APIError.unknown("This is unexpected. Missing APIError and GraphQLError.", ""), - mutationEvent)) + DataStoreError.api( + APIError.unknown("This is unexpected. Missing APIError and GraphQLError.", ""), + mutationEvent + )) finish(result: .success(nil)) return } @@ -102,8 +106,10 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { let errorType = AppSyncErrorType(errorTypeValue) switch errorType { case .conditionalCheck: - let payload = HubPayload(eventName: HubPayload.EventName.DataStore.conditionalSaveFailed, - data: mutationEvent) + let payload = HubPayload( + eventName: HubPayload.EventName.DataStore.conditionalSaveFailed, + data: mutationEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: payload) dataStoreConfiguration.errorHandler(DataStoreError.api(graphQLResponseError, mutationEvent)) finish(result: .success(nil)) @@ -175,8 +181,10 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { switch mutationType { case .create: - let error = DataStoreError.unknown("Should never get conflict unhandled for create mutation", - "This indicates something unexpected was returned from the service") + let error = DataStoreError.unknown( + "Should never get conflict unhandled for create mutation", + "This indicates something unexpected was returned from the service" + ) finish(result: .failure(error)) return case .delete: @@ -188,15 +196,17 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { private func getRemoteModel(_ extensions: [String: JSONValue]) -> Result, Error> { guard case let .object(data) = extensions["data"] else { - let error = DataStoreError.unknown("Missing remote model from the response from AppSync.", - "This indicates something unexpected was returned from the service") + let error = DataStoreError.unknown( + "Missing remote model from the response from AppSync.", + "This indicates something unexpected was returned from the service" + ) return .failure(error) } do { let serializedJSON = try JSONEncoder().encode(data) let decoder = JSONDecoder() decoder.dateDecodingStrategy = ModelDateFormatting.decodingStrategy - return .success(try decoder.decode(MutationSync.self, from: serializedJSON)) + return try .success(decoder.decode(MutationSync.self, from: serializedJSON)) } catch { return .failure(error) } @@ -219,9 +229,11 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { case .applyRemote: self.saveCreateOrUpdateMutation(remoteModel: remoteModel) case .retryLocal: - let request = GraphQLRequest.deleteMutation(of: localModel, - modelSchema: localModel.schema, - version: latestVersion) + let request = GraphQLRequest.deleteMutation( + of: localModel, + modelSchema: localModel.schema, + version: latestVersion + ) self.sendMutation(describedBy: request) case .retry(let model): guard let modelSchema = ModelRegistry.modelSchema(from: self.mutationEvent.modelName) else { @@ -230,9 +242,11 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { initialized. """) } - let request = GraphQLRequest.updateMutation(of: model, - modelSchema: modelSchema, - version: latestVersion) + let request = GraphQLRequest.updateMutation( + of: model, + modelSchema: modelSchema, + version: latestVersion + ) self.sendMutation(describedBy: request) } } @@ -262,9 +276,11 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { initialized. """) } - let request = GraphQLRequest.updateMutation(of: localModel, - modelSchema: modelSchema, - version: latestVersion) + let request = GraphQLRequest.updateMutation( + of: localModel, + modelSchema: modelSchema, + version: latestVersion + ) self.sendMutation(describedBy: request) case .retry(let model): guard let modelSchema = ModelRegistry.modelSchema(from: self.mutationEvent.modelName) else { @@ -273,9 +289,11 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { initialized. """) } - let request = GraphQLRequest.updateMutation(of: model, - modelSchema: modelSchema, - version: latestVersion) + let request = GraphQLRequest.updateMutation( + of: model, + modelSchema: modelSchema, + version: latestVersion + ) self.sendMutation(describedBy: request) } } @@ -288,7 +306,7 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { return } - guard let api = self.api else { + guard let api else { log.error("\(#function): API unexpectedly nil") let apiError = APIError.unknown("API unexpectedly nil", "") finish(result: .failure(apiError)) @@ -299,13 +317,13 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { Task { [weak self] in do { let result = try await api.mutate(request: apiRequest) - guard let self = self, !self.isCancelled else { + guard let self, !self.isCancelled else { self?.finish(result: .failure(APIError.operationError("Mutation operation cancelled", ""))) return } - self.log.verbose("sendMutationToCloud received asyncEvent: \(result)") - self.validate(cloudResult: result, request: apiRequest) + log.verbose("sendMutationToCloud received asyncEvent: \(result)") + validate(cloudResult: result, request: apiRequest) } catch { self?.finish(result: .failure(APIError.operationError("Failed to do mutation", "", error))) } @@ -319,7 +337,7 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { switch cloudResult { case .success(let mutationSyncResult): - guard let reconciliationQueue = reconciliationQueue else { + guard let reconciliationQueue else { let dataStoreError = DataStoreError.configuration( "reconciliationQueue is unexpectedly nil", """ @@ -359,10 +377,12 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { let identifier = remoteModel.model.identifier(schema: modelSchema) - storageAdapter.delete(untypedModelType: modelType, - modelSchema: modelSchema, - withIdentifier: identifier, - condition: nil) { response in + storageAdapter.delete( + untypedModelType: modelType, + modelSchema: modelSchema, + withIdentifier: identifier, + condition: nil + ) { response in switch response { case .failure(let dataStoreError): let error = DataStoreError.unknown("Delete failed \(dataStoreError)", "") @@ -397,8 +417,10 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { } } - private func saveMetadata(storageAdapter: StorageEngineAdapter, - inProcessModel: MutationSync) { + private func saveMetadata( + storageAdapter: StorageEngineAdapter, + inProcessModel: MutationSync + ) { log.verbose(#function) storageAdapter.save(inProcessModel.syncMetadata, condition: nil, eagerLoad: true) { result in switch result { @@ -430,17 +452,21 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { mutationType = .update } - guard let mutationEvent = try? MutationEvent(untypedModel: savedModel.model.instance, - mutationType: mutationType, - version: version) + guard let mutationEvent = try? MutationEvent( + untypedModel: savedModel.model.instance, + mutationType: mutationType, + version: version + ) else { let error = DataStoreError.unknown("Could not create MutationEvent", "") finish(result: .failure(error)) return } - let payload = HubPayload(eventName: HubPayload.EventName.DataStore.syncReceived, - data: mutationEvent) + let payload = HubPayload( + eventName: HubPayload.EventName.DataStore.syncReceived, + data: mutationEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: payload) finish(result: .success(mutationEvent)) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift index 40f9c04f06..a24b8d47d7 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore /// Publishes a mutation event to the specified Cloud API. Upon receipt of the API response, validates to ensure it is /// not a retriable error. If it is, attempts a retry until either success or terminal failure. Upon success or @@ -29,14 +29,16 @@ class SyncMutationToCloudOperation: AsynchronousOperation { private var currentAttemptNumber: Int private var authTypesIterator: AWSAuthorizationTypeIterator? - init(mutationEvent: MutationEvent, - getLatestSyncMetadata: @escaping () -> MutationSyncMetadata?, - api: APICategoryGraphQLBehavior, - authModeStrategy: AuthModeStrategy, - networkReachabilityPublisher: AnyPublisher? = nil, - currentAttemptNumber: Int = 1, - requestRetryablePolicy: RequestRetryablePolicy? = RequestRetryablePolicy(), - completion: @escaping GraphQLOperation>.ResultListener) async { + init( + mutationEvent: MutationEvent, + getLatestSyncMetadata: @escaping () -> MutationSyncMetadata?, + api: APICategoryGraphQLBehavior, + authModeStrategy: AuthModeStrategy, + networkReachabilityPublisher: AnyPublisher? = nil, + currentAttemptNumber: Int = 1, + requestRetryablePolicy: RequestRetryablePolicy? = RequestRetryablePolicy(), + completion: @escaping GraphQLOperation>.ResultListener + ) async { self.mutationEvent = mutationEvent self.getLatestSyncMetadata = getLatestSyncMetadata self.api = api @@ -48,8 +50,10 @@ class SyncMutationToCloudOperation: AsynchronousOperation { if let modelSchema = ModelRegistry.modelSchema(from: mutationEvent.modelName), let mutationType = GraphQLMutationType(rawValue: mutationEvent.mutationType) { - self.authTypesIterator = await authModeStrategy.authTypesFor(schema: modelSchema, - operation: mutationType.toModelOperation()) + self.authTypesIterator = await authModeStrategy.authTypesFor( + schema: modelSchema, + operation: mutationType.toModelOperation() + ) } super.init() @@ -151,10 +155,12 @@ class SyncMutationToCloudOperation: AsynchronousOperation { initialized. """) } - request = GraphQLRequest.deleteMutation(of: model, - modelSchema: modelSchema, - where: graphQLFilter, - version: version) + request = GraphQLRequest.deleteMutation( + of: model, + modelSchema: modelSchema, + where: graphQLFilter, + version: version + ) case .update: let model = try mutationEvent.decodeModel() guard let modelSchema = ModelRegistry.modelSchema(from: mutationEvent.modelName) else { @@ -163,10 +169,12 @@ class SyncMutationToCloudOperation: AsynchronousOperation { initialized. """) } - request = GraphQLRequest.updateMutation(of: model, - modelSchema: modelSchema, - where: graphQLFilter, - version: version) + request = GraphQLRequest.updateMutation( + of: model, + modelSchema: modelSchema, + where: graphQLFilter, + version: version + ) case .create: let model = try mutationEvent.decodeModel() guard let modelSchema = ModelRegistry.modelSchema(from: mutationEvent.modelName) else { @@ -175,9 +183,11 @@ class SyncMutationToCloudOperation: AsynchronousOperation { initialized. """) } - request = GraphQLRequest.createMutation(of: model, - modelSchema: modelSchema, - version: version) + request = GraphQLRequest.createMutation( + of: model, + modelSchema: modelSchema, + version: version + ) } } catch { let apiError = APIError.unknown("Couldn't decode model", "", error) @@ -185,8 +195,10 @@ class SyncMutationToCloudOperation: AsynchronousOperation { return nil } - let awsPluginOptions = AWSAPIPluginDataStoreOptions(authType: authType, - modelName: mutationEvent.modelName) + let awsPluginOptions = AWSAPIPluginDataStoreOptions( + authType: authType, + modelName: mutationEvent.modelName + ) request.options = GraphQLRequest.Options(pluginOptions: awsPluginOptions) return request } @@ -196,7 +208,7 @@ class SyncMutationToCloudOperation: AsynchronousOperation { /// completion handler /// - Parameter apiRequest: The GraphQLRequest used to create the mutation operation private func sendMutation(describedBy apiRequest: GraphQLRequest>) { - guard let api = api else { + guard let api else { log.error("\(#function): API unexpectedly nil") let apiError = APIError.unknown("API unexpectedly nil", "") finish(result: .failure(apiError)) @@ -224,7 +236,7 @@ class SyncMutationToCloudOperation: AsynchronousOperation { toCloudResult result: GraphQLResponse>, withAPIRequest apiRequest: GraphQLRequest> ) { - guard !self.isCancelled else { + guard !isCancelled else { Amplify.log.debug("SyncMutationToCloudOperation cancelled, aborting") return } @@ -286,9 +298,11 @@ class SyncMutationToCloudOperation: AsynchronousOperation { case .networkError(_, _, let error): // currently expecting APIOperationResponse to be an URLError let urlError = error as? URLError - advice = requestRetryablePolicy.retryRequestAdvice(urlError: urlError, - httpURLResponse: nil, - attemptNumber: currentAttemptNumber) + advice = requestRetryablePolicy.retryRequestAdvice( + urlError: urlError, + httpURLResponse: nil, + attemptNumber: currentAttemptNumber + ) // we can't unify the following two cases (case 1 and case 2) as they have different associated values. // should retry with a different authType if server returned "Unauthorized Error" @@ -302,18 +316,22 @@ class SyncMutationToCloudOperation: AsynchronousOperation { switch authError { case .sessionExpired, .signedOut: // use `userAuthenticationRequired` to ensure advice to retry is true. - advice = requestRetryablePolicy.retryRequestAdvice(urlError: URLError(.userAuthenticationRequired), - httpURLResponse: nil, - attemptNumber: currentAttemptNumber) + advice = requestRetryablePolicy.retryRequestAdvice( + urlError: URLError(.userAuthenticationRequired), + httpURLResponse: nil, + attemptNumber: currentAttemptNumber + ) default: // should retry with a different authType if request failed locally with any other AuthError advice = shouldRetryWithDifferentAuthType() } } case .httpStatusError(_, let httpURLResponse): - advice = requestRetryablePolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: currentAttemptNumber) + advice = requestRetryablePolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: currentAttemptNumber + ) default: break } @@ -325,8 +343,10 @@ class SyncMutationToCloudOperation: AsynchronousOperation { return RequestRetryAdvice(shouldRetry: shouldRetry, retryInterval: .milliseconds(0)) } - private func scheduleRetry(advice: RequestRetryAdvice, - withAuthType authType: AWSAuthorizationType? = nil) { + private func scheduleRetry( + advice: RequestRetryAdvice, + withAuthType authType: AWSAuthorizationType? = nil + ) { log.verbose("\(#function) scheduling retry for mutation \(advice)") mutationRetryNotifier = MutationRetryNotifier( advice: advice, diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift index db2ae3b9e4..bbb2826218 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore extension RemoteSyncEngine: AuthModeStrategyDelegate { @@ -29,10 +29,10 @@ extension RemoteSyncEngine: AuthModeStrategyDelegate { return isLoggedInWithOIDC } - guard let auth = auth else { + guard let auth else { return false } - return (try? await auth.getCurrentUser()) != nil + return await (try? auth.getCurrentUser()) != nil } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+IncomingEventReconciliationQueueEvent.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+IncomingEventReconciliationQueueEvent.swift index 7e3c4d23c7..ecc3b75f85 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+IncomingEventReconciliationQueueEvent.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+IncomingEventReconciliationQueueEvent.swift @@ -41,15 +41,17 @@ extension RemoteSyncEngine { stateMachine.notify(action: .initializedSubscriptions) case .started: log.verbose("[InitializeSubscription.6] RemoteSyncEngine IncomingEventReconciliationQueueEvent.started") - guard let api = self.api else { + guard let api else { let error = DataStoreError.internalOperation("api is unexpectedly `nil`", "", nil) stateMachine.notify(action: .errored(error)) return } remoteSyncTopicPublisher.send(.subscriptionsActivated) - stateMachine.notify(action: .activatedCloudSubscriptions(api, - mutationEventPublisher, - reconciliationQueue)) + stateMachine.notify(action: .activatedCloudSubscriptions( + api, + mutationEventPublisher, + reconciliationQueue + )) case .paused: remoteSyncTopicPublisher.send(.subscriptionsPaused) case .idle, .mutationEventDropped, .mutationEventApplied: diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Resolver.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Resolver.swift index 957051b8e6..ab6d7946b7 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Resolver.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Resolver.swift @@ -9,7 +9,7 @@ import Amplify import Combine extension RemoteSyncEngine { - struct Resolver { + enum Resolver { // swiftlint:disable cyclomatic_complexity static func resolve(currentState: State, action: Action) -> State { switch (currentState, action) { @@ -35,9 +35,11 @@ extension RemoteSyncEngine { case (.performingInitialSync, .errored(let error)): return .cleaningUp(error) - case (.activatingCloudSubscriptions, .activatedCloudSubscriptions(let api, - let mutationEventPublisher, - let reconciliationQueue)): + case (.activatingCloudSubscriptions, .activatedCloudSubscriptions( + let api, + let mutationEventPublisher, + let reconciliationQueue + )): return .activatingMutationQueue(api, mutationEventPublisher, reconciliationQueue) case (.activatingCloudSubscriptions, .errored(let error)): return .cleaningUp(error) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Retryable.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Retryable.swift index 8d4aa5a61a..92c8f328b1 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Retryable.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+Retryable.swift @@ -44,9 +44,11 @@ extension RemoteSyncEngine { urlErrorOptional = urlError } - let advice = requestRetryablePolicy.retryRequestAdvice(urlError: urlErrorOptional, - httpURLResponse: nil, - attemptNumber: currentAttemptNumber) + let advice = requestRetryablePolicy.retryRequestAdvice( + urlError: urlErrorOptional, + httpURLResponse: nil, + attemptNumber: currentAttemptNumber + ) return advice } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift index fd30c9ecae..34ea053a7c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore // swiftlint:disable type_body_length file_length class RemoteSyncEngine: RemoteSyncEngineBehavior { @@ -66,14 +66,16 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { /// Initializes the CloudSyncEngine with the specified storageAdapter as the provider for persistence of /// MutationEvents, sync metadata, and conflict resolution metadata. Immediately initializes the incoming mutation /// queue so it can begin accepting incoming mutations from DataStore. - convenience init(storageAdapter: StorageEngineAdapter, - dataStoreConfiguration: DataStoreConfiguration, - outgoingMutationQueue: OutgoingMutationQueueBehavior? = nil, - initialSyncOrchestratorFactory: InitialSyncOrchestratorFactory? = nil, - reconciliationQueueFactory: IncomingEventReconciliationQueueFactory? = nil, - stateMachine: StateMachine? = nil, - networkReachabilityPublisher: AnyPublisher? = nil, - requestRetryablePolicy: RequestRetryablePolicy? = nil) throws { + convenience init( + storageAdapter: StorageEngineAdapter, + dataStoreConfiguration: DataStoreConfiguration, + outgoingMutationQueue: OutgoingMutationQueueBehavior? = nil, + initialSyncOrchestratorFactory: InitialSyncOrchestratorFactory? = nil, + reconciliationQueueFactory: IncomingEventReconciliationQueueFactory? = nil, + stateMachine: StateMachine? = nil, + networkReachabilityPublisher: AnyPublisher? = nil, + requestRetryablePolicy: RequestRetryablePolicy? = nil + ) throws { let mutationDatabaseAdapter = try AWSMutationDatabaseAdapter(storageAdapter: storageAdapter) let awsMutationEventPublisher = AWSMutationEventPublisher(eventSource: mutationDatabaseAdapter) @@ -82,9 +84,11 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { let resolvedAuthStrategy: AuthModeStrategy = dataStoreConfiguration.authModeStrategyType.resolveStrategy() let outgoingMutationQueue = outgoingMutationQueue ?? - OutgoingMutationQueue(storageAdapter: storageAdapter, - dataStoreConfiguration: dataStoreConfiguration, - authModeStrategy: resolvedAuthStrategy) + OutgoingMutationQueue( + storageAdapter: storageAdapter, + dataStoreConfiguration: dataStoreConfiguration, + authModeStrategy: resolvedAuthStrategy + ) // swiftlint:disable line_length let reconciliationQueueFactory = reconciliationQueueFactory ?? AWSIncomingEventReconciliationQueue.init(modelSchemas:api:storageAdapter:syncExpressions:auth:authModeStrategy:modelReconciliationQueueFactory:disableSubscriptions:) @@ -93,35 +97,41 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { AWSInitialSyncOrchestrator.init(dataStoreConfiguration:authModeStrategy:api:reconciliationQueue:storageAdapter:) let resolver = RemoteSyncEngine.Resolver.resolve(currentState:action:) - let stateMachine = stateMachine ?? StateMachine(initialState: .notStarted, - resolver: resolver) + let stateMachine = stateMachine ?? StateMachine( + initialState: .notStarted, + resolver: resolver + ) let requestRetryablePolicy = requestRetryablePolicy ?? RequestRetryablePolicy() - self.init(storageAdapter: storageAdapter, - dataStoreConfiguration: dataStoreConfiguration, - authModeStrategy: resolvedAuthStrategy, - outgoingMutationQueue: outgoingMutationQueue, - mutationEventIngester: mutationDatabaseAdapter, - mutationEventPublisher: awsMutationEventPublisher, - initialSyncOrchestratorFactory: initialSyncOrchestratorFactory, - reconciliationQueueFactory: reconciliationQueueFactory, - stateMachine: stateMachine, - networkReachabilityPublisher: networkReachabilityPublisher, - requestRetryablePolicy: requestRetryablePolicy) + self.init( + storageAdapter: storageAdapter, + dataStoreConfiguration: dataStoreConfiguration, + authModeStrategy: resolvedAuthStrategy, + outgoingMutationQueue: outgoingMutationQueue, + mutationEventIngester: mutationDatabaseAdapter, + mutationEventPublisher: awsMutationEventPublisher, + initialSyncOrchestratorFactory: initialSyncOrchestratorFactory, + reconciliationQueueFactory: reconciliationQueueFactory, + stateMachine: stateMachine, + networkReachabilityPublisher: networkReachabilityPublisher, + requestRetryablePolicy: requestRetryablePolicy + ) } - init(storageAdapter: StorageEngineAdapter, - dataStoreConfiguration: DataStoreConfiguration, - authModeStrategy: AuthModeStrategy, - outgoingMutationQueue: OutgoingMutationQueueBehavior, - mutationEventIngester: MutationEventIngester, - mutationEventPublisher: MutationEventPublisher, - initialSyncOrchestratorFactory: @escaping InitialSyncOrchestratorFactory, - reconciliationQueueFactory: @escaping IncomingEventReconciliationQueueFactory, - stateMachine: StateMachine, - networkReachabilityPublisher: AnyPublisher?, - requestRetryablePolicy: RequestRetryablePolicy) { + init( + storageAdapter: StorageEngineAdapter, + dataStoreConfiguration: DataStoreConfiguration, + authModeStrategy: AuthModeStrategy, + outgoingMutationQueue: OutgoingMutationQueueBehavior, + mutationEventIngester: MutationEventIngester, + mutationEventPublisher: MutationEventPublisher, + initialSyncOrchestratorFactory: @escaping InitialSyncOrchestratorFactory, + reconciliationQueueFactory: @escaping IncomingEventReconciliationQueueFactory, + stateMachine: StateMachine, + networkReachabilityPublisher: AnyPublisher?, + requestRetryablePolicy: RequestRetryablePolicy + ) { self.storageAdapter = storageAdapter self.dataStoreConfiguration = dataStoreConfiguration self.authModeStrategy = authModeStrategy @@ -140,11 +150,11 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { self.stateMachineSink = self.stateMachine .$state .sink { [weak self] newState in - guard let self = self else { + guard let self else { return } - self.log.verbose("New state: \(newState)") - self.taskQueue.async { + log.verbose("New state: \(newState)") + taskQueue.async { await self.respond(to: newState) } } @@ -173,9 +183,11 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { case .activatingCloudSubscriptions: activateCloudSubscriptions() case .activatingMutationQueue(let api, let mutationEventPublisher, let reconciliationQueue): - startMutationQueue(api: api, - mutationEventPublisher: mutationEventPublisher, - reconciliationQueue: reconciliationQueue) + startMutationQueue( + api: api, + mutationEventPublisher: mutationEventPublisher, + reconciliationQueue: reconciliationQueue + ) case .notifyingSyncStarted: notifySyncStarted() @@ -280,18 +292,22 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { } } - private func initializeSubscriptions(api: APICategoryGraphQLBehavior, - storageAdapter: StorageEngineAdapter) async { + private func initializeSubscriptions( + api: APICategoryGraphQLBehavior, + storageAdapter: StorageEngineAdapter + ) async { log.debug("[InitializeSubscription] \(#function)") let syncableModelSchemas = ModelRegistry.modelSchemas.filter { $0.isSyncable } - reconciliationQueue = await reconciliationQueueFactory(syncableModelSchemas, - api, - storageAdapter, - dataStoreConfiguration.syncExpressions, - auth, - authModeStrategy, - nil, - dataStoreConfiguration.disableSubscriptions) + reconciliationQueue = await reconciliationQueueFactory( + syncableModelSchemas, + api, + storageAdapter, + dataStoreConfiguration.syncExpressions, + auth, + authModeStrategy, + nil, + dataStoreConfiguration.disableSubscriptions + ) reconciliationQueueSink = reconciliationQueue? .publisher .sink( @@ -303,17 +319,21 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { private func performInitialSync() { log.debug("[InitializeSubscription.6] \(#function)") - let initialSyncOrchestrator = initialSyncOrchestratorFactory(dataStoreConfiguration, - authModeStrategy, - api, - reconciliationQueue, - storageAdapter) + let initialSyncOrchestrator = initialSyncOrchestratorFactory( + dataStoreConfiguration, + authModeStrategy, + api, + reconciliationQueue, + storageAdapter + ) // Hold a reference so we can `reset` while initial sync is in process self.initialSyncOrchestrator = initialSyncOrchestrator - syncEventEmitter = SyncEventEmitter(initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + syncEventEmitter = SyncEventEmitter( + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) syncEventEmitterSink = syncEventEmitter? .publisher @@ -330,23 +350,23 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { ) initialSyncOrchestrator.sync { [weak self] result in - guard let self = self else { + guard let self else { return } if case .failure(let dataStoreError) = result { - self.log.error(dataStoreError.errorDescription) - self.log.error(dataStoreError.recoverySuggestion) + log.error(dataStoreError.errorDescription) + log.error(dataStoreError.recoverySuggestion) if let underlyingError = dataStoreError.underlyingError { - self.log.error("\(underlyingError)") + log.error("\(underlyingError)") } - self.stateMachine.notify(action: .errored(dataStoreError)) + stateMachine.notify(action: .errored(dataStoreError)) } else { - self.log.info("Successfully finished sync") + log.info("Successfully finished sync") - self.remoteSyncTopicPublisher.send(.performedInitialSync) - self.stateMachine.notify(action: .performedInitialSync) + remoteSyncTopicPublisher.send(.performedInitialSync) + stateMachine.notify(action: .performedInitialSync) } self.initialSyncOrchestrator = nil } @@ -354,7 +374,7 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { private func activateCloudSubscriptions() { log.debug(#function) - guard let reconciliationQueue = reconciliationQueue else { + guard let reconciliationQueue else { let error = DataStoreError.internalOperation("reconciliationQueue is unexpectedly `nil`", "", nil) stateMachine.notify(action: .errored(error)) return @@ -363,13 +383,17 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { reconciliationQueue.start() } - private func startMutationQueue(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) { + private func startMutationQueue( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { log.debug(#function) - outgoingMutationQueue.startSyncingToCloud(api: api, - mutationEventPublisher: mutationEventPublisher, - reconciliationQueue: reconciliationQueue) + outgoingMutationQueue.startSyncingToCloud( + api: api, + mutationEventPublisher: mutationEventPublisher, + reconciliationQueue: reconciliationQueue + ) remoteSyncTopicPublisher.send(.mutationQueueStarted) stateMachine.notify(action: .activatedMutationQueue) @@ -396,8 +420,10 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { private func notifySyncStarted() { resetCurrentAttemptNumber() log.verbose("[Lifecycle event 5]: syncStarted") - Amplify.Hub.dispatch(to: .dataStore, - payload: HubPayload(eventName: HubPayload.EventName.DataStore.syncStarted)) + Amplify.Hub.dispatch( + to: .dataStore, + payload: HubPayload(eventName: HubPayload.EventName.DataStore.syncStarted) + ) remoteSyncTopicPublisher.send(.syncStarted) stateMachine.notify(action: .notifiedSyncStarted) @@ -405,8 +431,10 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { private func onReceiveNetworkStatus(networkStatus: ReachabilityUpdate) { let networkStatusEvent = NetworkStatusEvent(active: networkStatus.isOnline) - let networkStatusEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.networkStatus, - data: networkStatusEvent) + let networkStatusEventPayload = HubPayload( + eventName: HubPayload.EventName.DataStore.networkStatus, + data: networkStatusEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: networkStatusEventPayload) } @@ -444,7 +472,7 @@ extension RemoteSyncEngine: Resettable { if let resettable = child.value as? Resettable { log.verbose("Resetting \(label)") await resettable.reset() - self.log.verbose("Resetting \(label): finished") + log.verbose("Resetting \(label): finished") } } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryable.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryable.swift index f215daeda0..b0c8529d9e 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryable.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryable.swift @@ -10,8 +10,10 @@ import Foundation struct RequestRetryAdvice { let shouldRetry: Bool let retryInterval: DispatchTimeInterval - init(shouldRetry: Bool, - retryInterval: DispatchTimeInterval = .seconds(60)) { + init( + shouldRetry: Bool, + retryInterval: DispatchTimeInterval = .seconds(60) + ) { self.shouldRetry = shouldRetry self.retryInterval = retryInterval } @@ -19,7 +21,9 @@ struct RequestRetryAdvice { } protocol RequestRetryable { - func retryRequestAdvice(urlError: URLError?, - httpURLResponse: HTTPURLResponse?, - attemptNumber: Int) -> RequestRetryAdvice + func retryRequestAdvice( + urlError: URLError?, + httpURLResponse: HTTPURLResponse?, + attemptNumber: Int + ) -> RequestRetryAdvice } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryablePolicy.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryablePolicy.swift index 220834d187..13cffd6ee8 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryablePolicy.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RequestRetryablePolicy.swift @@ -14,24 +14,28 @@ class RequestRetryablePolicy: RequestRetryable { private static let maxExponentForExponentialBackoff = 31 - public func retryRequestAdvice(urlError: URLError?, - httpURLResponse: HTTPURLResponse?, - attemptNumber: Int) -> RequestRetryAdvice { + public func retryRequestAdvice( + urlError: URLError?, + httpURLResponse: HTTPURLResponse?, + attemptNumber: Int + ) -> RequestRetryAdvice { var attemptNumber = attemptNumber if attemptNumber <= 0 { assertionFailure("attemptNumber should be > 0") attemptNumber = 1 } - if let urlError = urlError { + if let urlError { return determineRetryRequestAdvice(basedOn: urlError, attemptNumber: attemptNumber) } else { return determineRetryRequestAdvice(basedOn: httpURLResponse, attemptNumber: attemptNumber) } } - private func determineRetryRequestAdvice(basedOn urlError: URLError, - attemptNumber: Int) -> RequestRetryAdvice { + private func determineRetryRequestAdvice( + basedOn urlError: URLError, + attemptNumber: Int + ) -> RequestRetryAdvice { switch urlError.code { case .notConnectedToInternet, .dnsLookupFailed, @@ -51,10 +55,12 @@ class RequestRetryablePolicy: RequestRetryable { return RequestRetryAdvice(shouldRetry: false) } - private func determineRetryRequestAdvice(basedOn httpURLResponse: HTTPURLResponse?, - attemptNumber: Int) -> RequestRetryAdvice { + private func determineRetryRequestAdvice( + basedOn httpURLResponse: HTTPURLResponse?, + attemptNumber: Int + ) -> RequestRetryAdvice { /// If there was no error and no response, then we should not retry. - guard let httpURLResponse = httpURLResponse else { + guard let httpURLResponse else { return RequestRetryAdvice(shouldRetry: false) } @@ -97,14 +103,13 @@ class RequestRetryablePolicy: RequestRetryable { /// - Parameter response: The response to get the header from /// - Returns: The value of the "Retry-After" header, or nil if not present or not convertable to Int private func getRetryAfterHeaderValue(from response: HTTPURLResponse) -> Int? { - let waitTime: Int? - switch response.allHeaderFields["Retry-After"] { + let waitTime: Int? = switch response.allHeaderFields["Retry-After"] { case let retryTime as String: - waitTime = Int(retryTime) + Int(retryTime) case let retryTime as Int: - waitTime = retryTime + retryTime default: - waitTime = nil + nil } return waitTime diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift index 4a6d765aca..92319a2352 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift @@ -14,15 +14,16 @@ typealias DisableSubscriptions = () -> Bool // Used for testing: typealias IncomingEventReconciliationQueueFactory = - ([ModelSchema], - APICategoryGraphQLBehavior, - StorageEngineAdapter, - [DataStoreSyncExpression], - AuthCategoryBehavior?, - AuthModeStrategy, - ModelReconciliationQueueFactory?, - @escaping DisableSubscriptions -) async -> IncomingEventReconciliationQueue + ( + [ModelSchema], + APICategoryGraphQLBehavior, + StorageEngineAdapter, + [DataStoreSyncExpression], + AuthCategoryBehavior?, + AuthModeStrategy, + ModelReconciliationQueueFactory?, + @escaping DisableSubscriptions + ) async -> IncomingEventReconciliationQueue final class AWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueue { @@ -45,22 +46,24 @@ final class AWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueu } private let modelSchemasCount: Int - init(modelSchemas: [ModelSchema], - api: APICategoryGraphQLBehavior, - storageAdapter: StorageEngineAdapter, - syncExpressions: [DataStoreSyncExpression], - auth: AuthCategoryBehavior? = nil, - authModeStrategy: AuthModeStrategy, - modelReconciliationQueueFactory: ModelReconciliationQueueFactory? = nil, - disableSubscriptions: @escaping () -> Bool = { false }) async { + init( + modelSchemas: [ModelSchema], + api: APICategoryGraphQLBehavior, + storageAdapter: StorageEngineAdapter, + syncExpressions: [DataStoreSyncExpression], + auth: AuthCategoryBehavior? = nil, + authModeStrategy: AuthModeStrategy, + modelReconciliationQueueFactory: ModelReconciliationQueueFactory? = nil, + disableSubscriptions: @escaping () -> Bool = { false } + ) async { self.modelSchemasCount = modelSchemas.count - self.modelReconciliationQueueSinks.set([:]) + modelReconciliationQueueSinks.set([:]) self.eventReconciliationQueueTopic = CurrentValueSubject(.idle) - self.reconciliationQueues.set([:]) + reconciliationQueues.set([:]) self.reconciliationQueueConnectionStatus = [:] self.reconcileAndSaveQueue = ReconcileAndSaveQueue(modelSchemas) - if let modelReconciliationQueueFactory = modelReconciliationQueueFactory { + if let modelReconciliationQueueFactory { self.modelReconciliationQueueFactory = modelReconciliationQueueFactory } else { self.modelReconciliationQueueFactory = AWSModelReconciliationQueue.init @@ -80,7 +83,7 @@ final class AWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueu Running DataStore on watchOS with subscriptions enabled is only possible during special circumstances such as actively streaming audio. See https://github.com/aws-amplify/amplify-swift/pull/3368 for more details. """ - self.log.verbose(message) + log.verbose(message) } #endif @@ -94,21 +97,25 @@ final class AWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueu log.warn("Duplicate model name found: \(modelName), not subscribing") continue } - let queue = await self.modelReconciliationQueueFactory(modelSchema, - storageAdapter, - api, - reconcileAndSaveQueue, - modelPredicate, - auth, - authModeStrategy, - subscriptionsDisabled ? OperationDisabledIncomingSubscriptionEventPublisher() : nil) + let queue = await self.modelReconciliationQueueFactory( + modelSchema, + storageAdapter, + api, + reconcileAndSaveQueue, + modelPredicate, + auth, + authModeStrategy, + subscriptionsDisabled ? OperationDisabledIncomingSubscriptionEventPublisher() : nil + ) reconciliationQueues.with { reconciliationQueues in reconciliationQueues[modelName] = queue } log.verbose("[InitializeSubscription.5] Sink reconciliationQueues \(modelName) \(reconciliationQueues.get().count)") - let modelReconciliationQueueSink = queue.publisher.sink(receiveCompletion: onReceiveCompletion(completed:), - receiveValue: onReceiveValue(receiveValue:)) + let modelReconciliationQueueSink = queue.publisher.sink( + receiveCompletion: onReceiveCompletion(completed:), + receiveValue: onReceiveValue(receiveValue:) + ) modelReconciliationQueueSinks.with { modelReconciliationQueueSinks in modelReconciliationQueueSinks[modelName] = modelReconciliationQueueSink } @@ -209,14 +216,16 @@ extension AWSIncomingEventReconciliationQueue: DefaultLogger { extension AWSIncomingEventReconciliationQueue { static let factory: IncomingEventReconciliationQueueFactory = { modelSchemas, api, storageAdapter, syncExpressions, auth, authModeStrategy, _, disableSubscriptions in - await AWSIncomingEventReconciliationQueue(modelSchemas: modelSchemas, - api: api, - storageAdapter: storageAdapter, - syncExpressions: syncExpressions, - auth: auth, - authModeStrategy: authModeStrategy, - modelReconciliationQueueFactory: nil, - disableSubscriptions: disableSubscriptions) + await AWSIncomingEventReconciliationQueue( + modelSchemas: modelSchemas, + api: api, + storageAdapter: storageAdapter, + syncExpressions: syncExpressions, + auth: auth, + authModeStrategy: authModeStrategy, + modelReconciliationQueueFactory: nil, + disableSubscriptions: disableSubscriptions + ) } } @@ -237,7 +246,7 @@ extension AWSIncomingEventReconciliationQueue: Resettable { reconcileAndSaveQueue.cancelAllOperations() // Reset is used in internal testing only. Some operations get kicked off at this point and do not finish // We're sometimes hitting a deadlock when waiting for them to finish. Commenting this out and letting - // the tests continue onto the next works pretty well, but ideally ReconcileAndLocalSaveOperation's should + // the tests continue onto the next works pretty well, but ideally ReconcileAndLocalSaveOperation's should // always finish. We can uncomment this to explore a better fix that will still gives us test stability. // reconcileAndSaveQueue.waitUntilOperationsAreFinished() log.verbose("Resetting reconcileAndSaveQueue: finished") diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingSubscriptionEventPublisher.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingSubscriptionEventPublisher.swift index 76c4b7dc9a..69cd551e67 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingSubscriptionEventPublisher.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingSubscriptionEventPublisher.swift @@ -22,17 +22,21 @@ final class AWSIncomingSubscriptionEventPublisher: IncomingSubscriptionEventPubl return subscriptionEventSubject.eraseToAnyPublisher() } - init(modelSchema: ModelSchema, - api: APICategoryGraphQLBehavior, - modelPredicate: QueryPredicate?, - auth: AuthCategoryBehavior?, - authModeStrategy: AuthModeStrategy) async { + init( + modelSchema: ModelSchema, + api: APICategoryGraphQLBehavior, + modelPredicate: QueryPredicate?, + auth: AuthCategoryBehavior?, + authModeStrategy: AuthModeStrategy + ) async { self.subscriptionEventSubject = PassthroughSubject() - self.asyncEvents = await IncomingAsyncSubscriptionEventPublisher(modelSchema: modelSchema, - api: api, - modelPredicate: modelPredicate, - auth: auth, - authModeStrategy: authModeStrategy) + self.asyncEvents = await IncomingAsyncSubscriptionEventPublisher( + modelSchema: modelSchema, + api: api, + modelPredicate: modelPredicate, + auth: auth, + authModeStrategy: authModeStrategy + ) self.mapper = IncomingAsyncSubscriptionEventToAnyModelMapper() asyncEvents.subscribe(subscriber: mapper) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisher.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisher.swift index e9a89800dd..33850ed97d 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisher.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisher.swift @@ -47,12 +47,14 @@ final class IncomingAsyncSubscriptionEventPublisher: AmplifyCancellable { private let taskQueue: TaskQueue private let modelName: ModelName - init(modelSchema: ModelSchema, - api: APICategoryGraphQLBehavior, - modelPredicate: QueryPredicate?, - auth: AuthCategoryBehavior?, - authModeStrategy: AuthModeStrategy, - awsAuthService: AWSAuthServiceBehavior? = nil) async { + init( + modelSchema: ModelSchema, + api: APICategoryGraphQLBehavior, + modelPredicate: QueryPredicate?, + auth: AuthCategoryBehavior?, + authModeStrategy: AuthModeStrategy, + awsAuthService: AWSAuthServiceBehavior? = nil + ) async { self.onCreateConnected = false self.onUpdateConnected = false self.onDeleteConnected = false @@ -126,20 +128,20 @@ final class IncomingAsyncSubscriptionEventPublisher: AmplifyCancellable { return RetryableGraphQLSubscriptionOperation( requestStream: AsyncStream { continuation in for authType in authTypeProvider { - continuation.yield({ [weak self] in + continuation.yield { [weak self] in guard let self else { throw APIError.operationError("GraphQL subscription cancelled", "") } - return api.subscribe(request: await IncomingAsyncSubscriptionEventPublisher.makeAPIRequest( + return await api.subscribe(request: IncomingAsyncSubscriptionEventPublisher.makeAPIRequest( for: modelSchema, subscriptionType: subscriptionType.subscriptionType, api: api, auth: auth, authType: authType.awsAuthType, - awsAuthService: self.awsAuthService + awsAuthService: awsAuthService )) - }) + } } continuation.finish() } @@ -206,33 +208,41 @@ final class IncomingAsyncSubscriptionEventPublisher: AmplifyCancellable { } } - static func makeAPIRequest(for modelSchema: ModelSchema, - subscriptionType: GraphQLSubscriptionType, - api: APICategoryGraphQLBehavior, - auth: AuthCategoryBehavior?, - authType: AWSAuthorizationType?, - awsAuthService: AWSAuthServiceBehavior) async -> GraphQLRequest { + static func makeAPIRequest( + for modelSchema: ModelSchema, + subscriptionType: GraphQLSubscriptionType, + api: APICategoryGraphQLBehavior, + auth: AuthCategoryBehavior?, + authType: AWSAuthorizationType?, + awsAuthService: AWSAuthServiceBehavior + ) async -> GraphQLRequest { let request: GraphQLRequest if modelSchema.hasAuthenticationRules, let _ = auth, let tokenString = try? await awsAuthService.getUserPoolAccessToken(), case .success(let claims) = awsAuthService.getTokenClaims(tokenString: tokenString) { - request = GraphQLRequest.subscription(to: modelSchema, - subscriptionType: subscriptionType, - claims: claims, - authType: authType) + request = GraphQLRequest.subscription( + to: modelSchema, + subscriptionType: subscriptionType, + claims: claims, + authType: authType + ) } else if modelSchema.hasAuthenticationRules, let oidcAuthProvider = hasOIDCAuthProviderAvailable(api: api), let tokenString = try? await oidcAuthProvider.getLatestAuthToken(), case .success(let claims) = awsAuthService.getTokenClaims(tokenString: tokenString) { - request = GraphQLRequest.subscription(to: modelSchema, - subscriptionType: subscriptionType, - claims: claims, - authType: authType) + request = GraphQLRequest.subscription( + to: modelSchema, + subscriptionType: subscriptionType, + claims: claims, + authType: authType + ) } else { - request = GraphQLRequest.subscription(to: modelSchema, - subscriptionType: subscriptionType, - authType: authType) + request = GraphQLRequest.subscription( + to: modelSchema, + subscriptionType: subscriptionType, + authType: authType + ) } return request @@ -253,14 +263,14 @@ final class IncomingAsyncSubscriptionEventPublisher: AmplifyCancellable { func send(_ event: Event) { taskQueue.async { [weak self] in guard let self else { return } - self.incomingSubscriptionEvents.send(event) + incomingSubscriptionEvents.send(event) } } func send(completion: Subscribers.Completion) { taskQueue.async { [weak self] in guard let self else { return } - self.incomingSubscriptionEvents.send(completion: completion) + incomingSubscriptionEvents.send(completion: completion) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift index 03074d82e3..f247b299e4 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift @@ -76,14 +76,16 @@ final class AWSModelReconciliationQueue: ModelReconciliationQueue { return modelReconciliationQueueSubject.eraseToAnyPublisher() } - init(modelSchema: ModelSchema, - storageAdapter: StorageEngineAdapter?, - api: APICategoryGraphQLBehavior, - reconcileAndSaveQueue: ReconcileAndSaveOperationQueue, - modelPredicate: QueryPredicate?, - auth: AuthCategoryBehavior?, - authModeStrategy: AuthModeStrategy, - incomingSubscriptionEvents: IncomingSubscriptionEventPublisher? = nil) async { + init( + modelSchema: ModelSchema, + storageAdapter: StorageEngineAdapter?, + api: APICategoryGraphQLBehavior, + reconcileAndSaveQueue: ReconcileAndSaveOperationQueue, + modelPredicate: QueryPredicate?, + auth: AuthCategoryBehavior?, + authModeStrategy: AuthModeStrategy, + incomingSubscriptionEvents: IncomingSubscriptionEventPublisher? = nil + ) async { self.modelSchema = modelSchema self.storageAdapter = storageAdapter @@ -100,7 +102,7 @@ final class AWSModelReconciliationQueue: ModelReconciliationQueue { incomingSubscriptionEventQueue.isSuspended = true let resolvedIncomingSubscriptionEvents: IncomingSubscriptionEventPublisher - if let incomingSubscriptionEvents = incomingSubscriptionEvents { + if let incomingSubscriptionEvents { resolvedIncomingSubscriptionEvents = incomingSubscriptionEvents } else { resolvedIncomingSubscriptionEvents = await AWSIncomingSubscriptionEventPublisher( @@ -150,29 +152,31 @@ final class AWSModelReconciliationQueue: ModelReconciliationQueue { return } - let reconcileOp = ReconcileAndLocalSaveOperation(modelSchema: modelSchema, - remoteModels: remoteModels, - storageAdapter: storageAdapter) + let reconcileOp = ReconcileAndLocalSaveOperation( + modelSchema: modelSchema, + remoteModels: remoteModels, + storageAdapter: storageAdapter + ) var reconcileAndLocalSaveOperationSink: AnyCancellable? reconcileAndLocalSaveOperationSink = reconcileOp .publisher .sink(receiveCompletion: { [weak self] completion in - guard let self = self else { + guard let self else { return } - self.reconcileAndLocalSaveOperationSinks.with { $0.remove(reconcileAndLocalSaveOperationSink) } + reconcileAndLocalSaveOperationSinks.with { $0.remove(reconcileAndLocalSaveOperationSink) } if case .failure = completion { - self.modelReconciliationQueueSubject.send(completion: completion) + modelReconciliationQueueSubject.send(completion: completion) } }, receiveValue: { [weak self] value in - guard let self = self else { + guard let self else { return } switch value { case .mutationEventDropped(let modelName, let error): - self.modelReconciliationQueueSubject.send(.mutationEventDropped(modelName: modelName, error: error)) + modelReconciliationQueueSubject.send(.mutationEventDropped(modelName: modelName, error: error)) case .mutationEvent(let event): - self.modelReconciliationQueueSubject.send(.mutationEvent(event)) + modelReconciliationQueueSubject.send(.mutationEvent(event)) } }) reconcileAndLocalSaveOperationSinks.with { $0.insert(reconcileAndLocalSaveOperationSink) } @@ -241,7 +245,7 @@ extension AWSModelReconciliationQueue: Resettable { if let resettable = incomingSubscriptionEvents as? Resettable { log.verbose("Resetting incomingSubscriptionEvents") await resettable.reset() - self.log.verbose("Resetting incomingSubscriptionEvents: finished") + log.verbose("Resetting incomingSubscriptionEvents: finished") } log.verbose("Resetting incomingSubscriptionEventQueue") @@ -285,7 +289,7 @@ extension AWSModelReconciliationQueue { } private func isOperationDisabledError(_ errorMessage: String?, _ error: Error?) -> Bool { - if let errorMessage = errorMessage, + if let errorMessage, case .operationDisabled = AppSyncErrorType(errorMessage) { return true } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation+Resolver.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation+Resolver.swift index a723b1195e..332b8a17a8 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation+Resolver.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation+Resolver.swift @@ -8,7 +8,7 @@ import Amplify extension ReconcileAndLocalSaveOperation { - struct Resolver { + enum Resolver { /// It's not absolutely required to make `resolve` a static, but it helps in two ways: /// 1. It makes it easier to avoid retain cycles, since the reducer can't close over the state machine's owning diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift index 7ba4449c50..538adf5b0c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore // swiftlint:disable type_body_length file_length /// Reconciles an incoming model mutation with the stored model. If there is no conflict (e.g., the incoming model has @@ -26,9 +26,11 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { /// sent from the remote API as part of the mutation. typealias AppliedModel = MutationSync - let id: UUID = UUID() - private let workQueue = DispatchQueue(label: "com.amazonaws.ReconcileAndLocalSaveOperation", - target: DispatchQueue.global()) + let id: UUID = .init() + private let workQueue = DispatchQueue( + label: "com.amazonaws.ReconcileAndLocalSaveOperation", + target: DispatchQueue.global() + ) private weak var storageAdapter: StorageEngineAdapter? private let stateMachine: StateMachine @@ -44,16 +46,20 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { var isEagerLoad: Bool = true - init(modelSchema: ModelSchema, - remoteModels: [RemoteModel], - storageAdapter: StorageEngineAdapter?, - stateMachine: StateMachine? = nil) { + init( + modelSchema: ModelSchema, + remoteModels: [RemoteModel], + storageAdapter: StorageEngineAdapter?, + stateMachine: StateMachine? = nil + ) { self.modelSchema = modelSchema self.remoteModels = remoteModels self.storageAdapter = storageAdapter self.stopwatch = Stopwatch() - self.stateMachine = stateMachine ?? StateMachine(initialState: .waiting, - resolver: Resolver.resolve(currentState:action:)) + self.stateMachine = stateMachine ?? StateMachine( + initialState: .waiting, + resolver: Resolver.resolve(currentState:action:) + ) self.mutationEventPublisher = PassthroughSubject() self.cancellables = Set() @@ -69,11 +75,11 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { self.stateMachineSink = self.stateMachine .$state .sink { [weak self] newState in - guard let self = self else { + guard let self else { return } - self.log.verbose("New state: \(newState)") - self.workQueue.async { + log.verbose("New state: \(newState)") + workQueue.async { self.respond(to: newState) } } @@ -128,7 +134,7 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { return } - guard let storageAdapter = storageAdapter else { + guard let storageAdapter else { let error = DataStoreError.nilStorageAdapter() notifyDropped(count: remoteModels.count, error: error) stateMachine.notify(action: .errored(error)) @@ -144,17 +150,17 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { try storageAdapter.transaction { self.queryLocalMetadata(remoteModels) .subscribe(on: workQueue) - .map { (remoteModels, localMetadatas) in + .map { remoteModels, localMetadatas in self.getDispositions(for: remoteModels, localMetadatas: localMetadatas) } .flatMap { dispositions in self.queryPendingMutations(withModels: dispositions.map(\.remoteModel.model)) .map { pendingMutations in (pendingMutations, dispositions) } } - .map { (pendingMutations, dispositions) in + .map { pendingMutations, dispositions in self.separateDispositions(pendingMutations: pendingMutations, dispositions: dispositions) } - .flatMap { (dispositions, dispositionOnlyApplyMetadata) in + .flatMap { dispositions, dispositionOnlyApplyMetadata in self.waitAllPublisherFinishes(publishers: dispositionOnlyApplyMetadata.map(self.saveMetadata(disposition:))) .flatMap { _ in self.applyRemoteModelsDispositions(dispositions) } } @@ -267,7 +273,8 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { do { let localMetadatas = try storageAdapter.queryMutationSyncMetadata( for: remoteModels.map { $0.model.identifier }, - modelName: self.modelSchema.name) + modelName: self.modelSchema.name + ) result = .success((remoteModels, localMetadatas)) } catch { let error = DataStoreError(error: error) @@ -278,14 +285,18 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { } } - func getDispositions(for remoteModels: [RemoteModel], - localMetadatas: [LocalMetadata]) -> [RemoteSyncReconciler.Disposition] { + func getDispositions( + for remoteModels: [RemoteModel], + localMetadatas: [LocalMetadata] + ) -> [RemoteSyncReconciler.Disposition] { guard !remoteModels.isEmpty else { return [] } - let dispositions = RemoteSyncReconciler.getDispositions(remoteModels, - localMetadatas: localMetadatas) + let dispositions = RemoteSyncReconciler.getDispositions( + remoteModels, + localMetadatas: localMetadatas + ) notifyDropped(count: remoteModels.count - dispositions.count) return dispositions } @@ -297,9 +308,9 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { let operation: Future switch disposition { case .create, .update: - operation = self.save(storageAdapter: storageAdapter, remoteModel: disposition.remoteModel) + operation = save(storageAdapter: storageAdapter, remoteModel: disposition.remoteModel) case .delete: - operation = self.delete(storageAdapter: storageAdapter, remoteModel: disposition.remoteModel) + operation = delete(storageAdapter: storageAdapter, remoteModel: disposition.remoteModel) } return operation @@ -314,14 +325,14 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { func applyRemoteModelsDispositions( _ dispositions: [RemoteSyncReconciler.Disposition] ) -> Future { - guard !self.isCancelled else { - self.log.info("\(#function) - cancelled, aborting") + guard !isCancelled else { + log.info("\(#function) - cancelled, aborting") return Future { $0(.successfulVoid) } } - guard let storageAdapter = self.storageAdapter else { + guard let storageAdapter else { let error = DataStoreError.nilStorageAdapter() - self.notifyDropped(count: dispositions.count, error: error) + notifyDropped(count: dispositions.count, error: error) return Future { $0(.failure(error)) } } @@ -333,7 +344,7 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { applyRemoteModelsDisposition(storageAdapter: storageAdapter, disposition: $0) } - return self.waitAllPublisherFinishes(publishers: publishers) + return waitAllPublisherFinishes(publishers: publishers) } enum ApplyRemoteModelResult { @@ -341,8 +352,10 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { case dropped } - private func delete(storageAdapter: StorageEngineAdapter, - remoteModel: RemoteModel) -> Future { + private func delete( + storageAdapter: StorageEngineAdapter, + remoteModel: RemoteModel + ) -> Future { Future { promise in guard let modelType = ModelRegistry.modelType(from: self.modelSchema.name) else { let error = DataStoreError.invalidModelName(self.modelSchema.name) @@ -350,10 +363,12 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { return } - storageAdapter.delete(untypedModelType: modelType, - modelSchema: self.modelSchema, - withIdentifier: remoteModel.model.identifier(schema: self.modelSchema), - condition: nil) { response in + storageAdapter.delete( + untypedModelType: modelType, + modelSchema: self.modelSchema, + withIdentifier: remoteModel.model.identifier(schema: self.modelSchema), + condition: nil + ) { response in switch response { case .failure(let dataStoreError): self.notifyDropped(error: dataStoreError) @@ -402,7 +417,7 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { private func saveMetadata( disposition: RemoteSyncReconciler.Disposition ) -> AnyPublisher { - guard let storageAdapter = self.storageAdapter else { + guard let storageAdapter else { return Just(()).eraseToAnyPublisher() } return saveMetadata(storageAdapter: storageAdapter, remoteModel: disposition.remoteModel, mutationType: disposition.mutationType) @@ -418,7 +433,7 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { ) -> AnyPublisher { switch result { case .applied(let remoteModel, let appliedModel): - return self.saveMetadata(storageAdapter: storageAdapter, remoteModel: remoteModel, mutationType: mutationType) + return saveMetadata(storageAdapter: storageAdapter, remoteModel: remoteModel, mutationType: mutationType) .map { MutationSync(model: appliedModel.model, syncMetadata: $0) } .map { [weak self] in self?.notify(appliedModel: $0, mutationType: mutationType) } .eraseToAnyPublisher() @@ -464,11 +479,13 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { } let modelIdentifier = appliedModel.model.instance.identifier(schema: modelSchema).stringValue - let mutationEvent = MutationEvent(modelId: modelIdentifier, - modelName: modelSchema.name, - json: json, - mutationType: mutationType, - version: appliedModel.syncMetadata.version) + let mutationEvent = MutationEvent( + modelId: modelIdentifier, + modelName: modelSchema.name, + json: json, + mutationType: mutationType, + version: appliedModel.syncMetadata.version + ) mutationEventPublisher.send(.mutationEvent(mutationEvent)) } @@ -486,14 +503,18 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { } let modelIdentifier = remoteModel.model.instance.identifier(schema: modelSchema).stringValue - let mutationEvent = MutationEvent(modelId: modelIdentifier, - modelName: modelSchema.name, - json: json, - mutationType: mutationType, - version: remoteModel.syncMetadata.version) - - let payload = HubPayload(eventName: HubPayload.EventName.DataStore.syncReceived, - data: mutationEvent) + let mutationEvent = MutationEvent( + modelId: modelIdentifier, + modelName: modelSchema.name, + json: json, + mutationType: mutationType, + version: remoteModel.syncMetadata.version + ) + + let payload = HubPayload( + eventName: HubPayload.EventName.DataStore.syncReceived, + data: mutationEvent + ) Amplify.Hub.dispatch(to: .dataStore, payload: payload) } @@ -509,7 +530,7 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { .unknown("\(name) did not fulfill promise", AmplifyErrorMessages.shouldNotHappenReportBugToAWS(), nil) } - private func waitAllPublisherFinishes(publishers: [AnyPublisher]) -> Future { + private func waitAllPublisherFinishes(publishers: [AnyPublisher]) -> Future { Future { promise in Publishers.MergeMany(publishers) .collect() diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveQueue.swift index 30434dc04e..a8334eea0a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveQueue.swift @@ -6,9 +6,9 @@ // import Amplify +import AWSPluginsCore import Combine import Foundation -import AWSPluginsCore protocol ReconcileAndSaveOperationQueue { func addOperation(_ operation: ReconcileAndLocalSaveOperation, modelName: String) @@ -43,8 +43,10 @@ enum ReconcileAndSaveQueueEvent { /// continue to operate. class ReconcileAndSaveQueue: ReconcileAndSaveOperationQueue { - private let serialQueue = DispatchQueue(label: "com.amazonaws.ReconcileAndSaveQueue.serialQueue", - target: DispatchQueue.global()) + private let serialQueue = DispatchQueue( + label: "com.amazonaws.ReconcileAndSaveQueue.serialQueue", + target: DispatchQueue.global() + ) private let reconcileAndSaveQueue: OperationQueue private var modelReconcileAndSaveOperations: [String: [UUID: ReconcileAndLocalSaveOperation]] private var reconcileAndLocalSaveOperationSinks: AtomicValue> @@ -90,7 +92,7 @@ class ReconcileAndSaveQueue: ReconcileAndSaveOperationQueue { func cancelOperations(modelName: String) { serialQueue.async { if let operations = self.modelReconcileAndSaveOperations[modelName] { - operations.values.forEach { operation in + for operation in operations.values { operation.cancel() } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift index df95b21a8a..7c006b4f92 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift @@ -8,7 +8,7 @@ import Amplify /// Reconciles incoming sync mutations with the state of the local store, and mutation queue. -struct RemoteSyncReconciler { +enum RemoteSyncReconciler { typealias LocalMetadata = ReconcileAndLocalSaveOperation.LocalMetadata typealias RemoteModel = ReconcileAndLocalSaveOperation.RemoteModel @@ -50,24 +50,24 @@ struct RemoteSyncReconciler { $1.model.identifier: ($0[$1.model.identifier] ?? []) + [$1] ], uniquingKeysWith: { $1 }) } - + let optimizedRemoteModels = remoteModelsGroupByIdentifier.values.compactMap { $0.sorted(by: { $0.syncMetadata.version > $1.syncMetadata.version }).first } - + guard !optimizedRemoteModels.isEmpty else { return [] } - + guard !localMetadatas.isEmpty else { return optimizedRemoteModels.compactMap { getDisposition($0, localMetadata: nil) } } - + let metadataByModelId = localMetadatas.reduce(into: [:]) { $0[$1.modelId] = $1 } let dispositions = optimizedRemoteModels.compactMap { getDisposition($0, localMetadata: metadataByModelId[$0.model.identifier]) } - + return dispositions } @@ -85,7 +85,7 @@ struct RemoteSyncReconciler { /// - localMetadata: metadata corresponding to the remote model /// - Returns: disposition of the model, `nil` if to be dropped static func getDisposition(_ remoteModel: RemoteModel, localMetadata: LocalMetadata?) -> Disposition? { - guard let localMetadata = localMetadata else { + guard let localMetadata else { return remoteModel.syncMetadata.deleted ? nil : .create(remoteModel) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/DataStoreError+Plugin.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/DataStoreError+Plugin.swift index 812501bacc..346376521a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/DataStoreError+Plugin.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/DataStoreError+Plugin.swift @@ -10,9 +10,11 @@ import Amplify /// Convenience error types extension DataStoreError { - static func nilAPIHandle(file: StaticString = #file, - function: StaticString = #function, - line: UInt = #line) -> DataStoreError { + static func nilAPIHandle( + file: StaticString = #file, + function: StaticString = #function, + line: UInt = #line + ) -> DataStoreError { .internalOperation( "The reference to Amplify API is unexpectedly nil in an internal operation", """ @@ -23,9 +25,11 @@ extension DataStoreError { ) } - static func nilReconciliationQueue(file: StaticString = #file, - function: StaticString = #function, - line: UInt = #line) -> DataStoreError { + static func nilReconciliationQueue( + file: StaticString = #file, + function: StaticString = #function, + line: UInt = #line + ) -> DataStoreError { .internalOperation( "The reference to IncomingEventReconciliationQueue is unexpectedly nil in an internal operation", """ @@ -37,9 +41,11 @@ extension DataStoreError { ) } - static func nilStorageAdapter(file: StaticString = #file, - function: StaticString = #function, - line: UInt = #line) -> DataStoreError { + static func nilStorageAdapter( + file: StaticString = #file, + function: StaticString = #function, + line: UInt = #line + ) -> DataStoreError { .internalOperation( "storageAdapter is unexpectedly nil in an internal operation", """ diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Model+Compare.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Model+Compare.swift index ca9595dbf1..5a7c8cf4bd 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Model+Compare.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Model+Compare.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation // swiftlint:disable cyclomatic_complexity extension ModelSchema { @@ -113,15 +113,18 @@ extension ModelSchema { return false } case .enum: + // swiftformat:disable typeSugar // swiftlint:disable syntactic_sugar guard case .some(Optional.some(let value1Optional)) = value1, - case .some(Optional.some(let value2Optional)) = value2 else { + case .some(Optional.some(let value2Optional)) = value2 + else { if value1 == nil && value2 == nil { continue } return false } // swiftlint:enable syntactic_sugar + // swiftformat:enable typeSugar let enumValue1Optional = (value1Optional as? EnumPersistable)?.rawValue let enumValue2Optional = (value2Optional as? EnumPersistable)?.rawValue if !compare(enumValue1Optional, enumValue2Optional) { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Extensions.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Extensions.swift index 7d2057528e..6b9900f136 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Extensions.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Extensions.swift @@ -6,8 +6,8 @@ // import Amplify -import Dispatch import AWSPluginsCore +import Dispatch extension MutationEvent { // Consecutive operations that modify a model results in a sequence of pending mutation events that @@ -35,10 +35,12 @@ extension MutationEvent { // For a given model `id`, checks the version of the head of pending mutation event queue // against the API response version in `mutationSync` and saves it in the mutation event table if // the response version is a newer one - static func reconcilePendingMutationEventsVersion(sent mutationEvent: MutationEvent, - received mutationSync: MutationSync, - storageAdapter: StorageEngineAdapter, - completion: @escaping DataStoreCallback) { + static func reconcilePendingMutationEventsVersion( + sent mutationEvent: MutationEvent, + received mutationSync: MutationSync, + storageAdapter: StorageEngineAdapter, + completion: @escaping DataStoreCallback + ) { MutationEvent.pendingMutationEvents( forMutationEvent: mutationEvent, storageAdapter: storageAdapter @@ -52,9 +54,11 @@ extension MutationEvent { return } - guard let reconciledEvent = reconcile(pendingMutationEvent: existingEvent, - with: mutationEvent, - responseMutationSync: mutationSync) else { + guard let reconciledEvent = reconcile( + pendingMutationEvent: existingEvent, + with: mutationEvent, + responseMutationSync: mutationSync + ) else { completion(.success(())) return } @@ -71,9 +75,11 @@ extension MutationEvent { } } - static func reconcile(pendingMutationEvent: MutationEvent, - with requestMutationEvent: MutationEvent, - responseMutationSync: MutationSync) -> MutationEvent? { + static func reconcile( + pendingMutationEvent: MutationEvent, + with requestMutationEvent: MutationEvent, + responseMutationSync: MutationSync + ) -> MutationEvent? { // return if version of the pending mutation event is not nil and // is >= version contained in the response if pendingMutationEvent.version != nil && diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift index d84dad4ce7..b84665f1de 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift @@ -57,9 +57,11 @@ extension MutationEvent { ) } - private static func pendingMutationEvents(for modelIds: [(String, String)], - storageAdapter: StorageEngineAdapter, - completion: @escaping DataStoreCallback<[MutationEvent]>) { + private static func pendingMutationEvents( + for modelIds: [(String, String)], + storageAdapter: StorageEngineAdapter, + completion: @escaping DataStoreCallback<[MutationEvent]> + ) { Task { let fields = MutationEvent.keys let predicate = (fields.inProcess == false || fields.inProcess == nil) @@ -77,11 +79,13 @@ extension MutationEvent { do { let mutationEvents = try await withCheckedThrowingContinuation { continuation in - storageAdapter.query(MutationEvent.self, - predicate: final, - sort: [sort], - paginationInput: nil, - eagerLoad: true) { result in + storageAdapter.query( + MutationEvent.self, + predicate: final, + sort: [sort], + paginationInput: nil, + eagerLoad: true + ) { result in continuation.resume(with: result) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/SQLiteResultError.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/SQLiteResultError.swift index 60f1ba14d5..ec57fc6b3a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/SQLiteResultError.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/SQLiteResultError.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import SQLite import SQLite3 -import Amplify /// Checks for specific SQLLite error codes /// See https://sqlite.org/rescode.html#primary_result_code_list @@ -28,7 +28,8 @@ enum SQLiteResultError { init?(from dataStoreError: DataStoreError) { guard case let .invalidOperation(error) = dataStoreError, let resultError = error as? Result, - case .error(let message, let code, let statement) = resultError else { + case .error(let message, let code, let statement) = resultError + else { return nil } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/StateMachine.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/StateMachine.swift index 55855b1959..8b9b83c140 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/StateMachine.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/StateMachine.swift @@ -12,8 +12,10 @@ import Foundation class StateMachine { typealias Reducer = (State, Action) -> State - private let queue = DispatchQueue(label: "com.amazonaws.Amplify.StateMachine<\(State.self), \(Action.self)>", - target: DispatchQueue.global()) + private let queue = DispatchQueue( + label: "com.amazonaws.Amplify.StateMachine<\(State.self), \(Action.self)>", + target: DispatchQueue.global() + ) private var reducer: Reducer @Published var state: State diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Stopwatch.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Stopwatch.swift index c2e0111944..58032907b9 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Stopwatch.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/Stopwatch.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// A simple implementation of a stopwatch used for gathering metrics of elapsed time. class Stopwatch { @@ -28,7 +28,7 @@ class Stopwatch { /// - Returns: the elapsed time in seconds func lap() -> Double { lock.execute { - guard let lapStart = lapStart else { + guard let lapStart else { return 0 } @@ -50,7 +50,7 @@ class Stopwatch { startTime = nil } - guard let startTime = startTime else { + guard let startTime else { return 0 } let endTime = DispatchTime.now() diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStoreLocalStoreTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStoreLocalStoreTests.swift index 32a80b1735..2e7a2335c9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStoreLocalStoreTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStoreLocalStoreTests.swift @@ -7,8 +7,8 @@ import XCTest -import AWSPluginsCore import AmplifyTestCommon +import AWSPluginsCore @testable import Amplify @testable import AWSDataStorePlugin @@ -40,7 +40,7 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { let post = Post.keys let predicate = (post.id <= 1 && post.title == "title1") || (post.rating > 2 && post.status == PostStatus.private) - + let queriedPosts = try await Amplify.DataStore.query(Post.self, where: predicate) XCTAssertEqual(queriedPosts.count, 2) } @@ -59,11 +59,11 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { let queriedPosts = try await Amplify.DataStore.query(Post.self, paginate: .page(0, limit: 10)) XCTAssertEqual(queriedPosts.count, 10) posts.append(contentsOf: queriedPosts) - + let queriedPosts2 = try await Amplify.DataStore.query(Post.self, paginate: .page(1, limit: 10)) XCTAssertEqual(queriedPosts2.count, 5) posts.append(contentsOf: queriedPosts2) - + let idSet = Set(posts.map { $0.id }) XCTAssertEqual(idSet.count, 15) } @@ -103,9 +103,13 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { setUp(withModels: TestModelRegistration()) _ = try await setUpLocalStore(numberOfPosts: 50) - let posts = try await Amplify.DataStore.query(Post.self, - sort: .by(.ascending(Post.keys.rating), - .descending(Post.keys.title))) + let posts = try await Amplify.DataStore.query( + Post.self, + sort: .by( + .ascending(Post.keys.rating), + .descending(Post.keys.title) + ) + ) var previousRating: Double = 0 for post in posts { guard let rating = post.rating else { @@ -141,9 +145,11 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { setUp(withModels: TestModelRegistration()) _ = try await setUpLocalStore(numberOfPosts: 20) - let posts = try await Amplify.DataStore.query(Post.self, - where: Post.keys.rating >= 2, - sort: .ascending(Post.keys.rating)) + let posts = try await Amplify.DataStore.query( + Post.self, + where: Post.keys.rating >= 2, + sort: .ascending(Post.keys.rating) + ) var previousRating: Double = 0 for post in posts { @@ -170,10 +176,14 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { func testQueryWithSortAndPagintate() async throws { setUp(withModels: TestModelRegistration()) _ = try await setUpLocalStore(numberOfPosts: 20) - let posts = try await Amplify.DataStore.query(Post.self, - sort: .by(.ascending(Post.keys.rating), - .descending(Post.keys.title)), - paginate: .page(0, limit: 10)) + let posts = try await Amplify.DataStore.query( + Post.self, + sort: .by( + .ascending(Post.keys.rating), + .descending(Post.keys.title) + ), + paginate: .page(0, limit: 10) + ) XCTAssertEqual(posts.count, 10) var previousRating: Double = 0 @@ -201,10 +211,12 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { let filteredPosts = localPosts.filter { $0.rating! >= 2.0 } let count = filteredPosts.count - let posts = try await Amplify.DataStore.query(Post.self, - where: Post.keys.rating >= 2, - sort: .ascending(Post.keys.rating), - paginate: .page(0, limit: 10)) + let posts = try await Amplify.DataStore.query( + Post.self, + where: Post.keys.rating >= 2, + sort: .ascending(Post.keys.rating), + paginate: .page(0, limit: 10) + ) if count >= 10 { XCTAssertEqual(posts.count, 10) } else { @@ -237,17 +249,21 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { setUp(withModels: TestModelRegistration()) _ = try await setUpLocalStore(numberOfPosts: 50) - let queriedPosts = try await Amplify.DataStore.query(Post.self, - where: Post.keys.rating >= 2) - + let queriedPosts = try await Amplify.DataStore.query( + Post.self, + where: Post.keys.rating >= 2 + ) + var posts = [Post]() var currentPage: UInt = 0 var shouldRepeat = true repeat { - let returnPosts = try await Amplify.DataStore.query(Post.self, - where: Post.keys.rating >= 2, - sort: .ascending(Post.keys.rating), - paginate: .page(currentPage, limit: 10)) + let returnPosts = try await Amplify.DataStore.query( + Post.self, + where: Post.keys.rating >= 2, + sort: .ascending(Post.keys.rating), + paginate: .page(currentPage, limit: 10) + ) posts.append(contentsOf: returnPosts) if returnPosts.count == 10 { currentPage += 1 @@ -420,7 +436,7 @@ class AWSDataStoreLocalStoreTests: LocalStoreIntegrationTestBase { let posts = try await Amplify.DataStore.query(Post.self) XCTAssertEqual(posts.count, numberOfPosts) - let randomTitleNumber = String(Int.random(in: 0.. [Post] { - let posts = (0...self, from: data) + let result = try decoder.decode(DataStoreListDecoderHarness.self, from: data) XCTAssertNil(result.listProvider) } @@ -90,14 +90,14 @@ class DataStoreListDecoderTests: BaseDataStoreTests { "associatedId": "123" ] let data = try encoder.encode(json) - let result = try self.decoder.decode(DataStoreListDecoderHarness.self, from: data) + let result = try decoder.decode(DataStoreListDecoderHarness.self, from: data) XCTAssertNil(result.listProvider) } func testDataStoreListDecoderShouldNotDecodeJSONString() throws { let json: JSONValue = "JSONString" let data = try encoder.encode(json) - let result = try self.decoder.decode(DataStoreListDecoderHarness.self, from: data) + let result = try decoder.decode(DataStoreListDecoderHarness.self, from: data) XCTAssertNil(result.listProvider) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderFunctionalTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderFunctionalTests.swift index 689448904d..5643738052 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderFunctionalTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderFunctionalTests.swift @@ -16,8 +16,10 @@ class DataStoreListProviderFunctionalTests: BaseDataStoreTests { func testDataStoreListProviderWithAssociationDataShouldLoad() async throws { let postId = preparePost4DataForTest() - let provider = DataStoreListProvider(metadata: .init(dataStoreAssociatedIdentifiers: [postId], - dataStoreAssociatedFields: ["post"])) + let provider = DataStoreListProvider(metadata: .init( + dataStoreAssociatedIdentifiers: [postId], + dataStoreAssociatedFields: ["post"] + )) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") return diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderTests.swift index d2539c4193..6d9035947f 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreListProviderTests.swift @@ -48,8 +48,10 @@ class DataStoreListProviderTests: XCTestCase { } func testInitWithAssociationDataShouldBeInNotLoadedState() { - let provider = DataStoreListProvider(metadata: .init(dataStoreAssociatedIdentifiers: ["id"], - dataStoreAssociatedFields: ["field"])) + let provider = DataStoreListProvider(metadata: .init( + dataStoreAssociatedIdentifiers: ["id"], + dataStoreAssociatedFields: ["field"] + )) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") return @@ -59,12 +61,16 @@ class DataStoreListProviderTests: XCTestCase { func testNotLoadedStateLoadSuccess() async throws { mockDataStorePlugin.responders[.queryModelsListener] = QueryModelsResponder { _, _, _, _ in - return .success([Comment4(content: "content"), - Comment4(content: "content")]) + return .success([ + Comment4(content: "content"), + Comment4(content: "content") + ]) } - let provider = DataStoreListProvider(metadata: .init(dataStoreAssociatedIdentifiers: ["postId"], - dataStoreAssociatedFields: ["post"])) + let provider = DataStoreListProvider(metadata: .init( + dataStoreAssociatedIdentifiers: ["postId"], + dataStoreAssociatedFields: ["post"] + )) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") return @@ -85,7 +91,7 @@ class DataStoreListProviderTests: XCTestCase { XCTFail("Should be loaded") return } - + let results = try await listProvider.load() XCTAssertEqual(results.count, 2) } @@ -95,9 +101,11 @@ class DataStoreListProviderTests: XCTestCase { QueryModelsResponder { _, _, _, _ in return .failure(DataStoreError.internalOperation("", "", nil)) } - - let provider = DataStoreListProvider(metadata: .init(dataStoreAssociatedIdentifiers: ["postId"], - dataStoreAssociatedFields: ["post"])) + + let provider = DataStoreListProvider(metadata: .init( + dataStoreAssociatedIdentifiers: ["postId"], + dataStoreAssociatedFields: ["post"] + )) guard case .notLoaded = provider.loadedState else { XCTFail("Should not be loaded") return diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/QueryPredicateTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/QueryPredicateTests.swift index 77bd4cea56..aeff126f93 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/QueryPredicateTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/QueryPredicateTests.swift @@ -19,11 +19,11 @@ class QueryPredicateTests: XCTestCase { encoder.outputFormatting = [.sortedKeys] return encoder }() - + var encoder: JSONEncoder { _encoder } - + /// it should create a simple `QueryPredicateOperation` func testSingleQueryPredicateOperation() { let post = Post.keys @@ -47,7 +47,7 @@ class QueryPredicateTests: XCTestCase { ) XCTAssertEqual(predicate, expected) - + let predicateString = String(data: try! encoder.encode(predicate), encoding: .utf8)! let expectedString = String(data: try! encoder.encode(expected), encoding: .utf8)! XCTAssert(predicateString == expectedString) @@ -83,7 +83,7 @@ class QueryPredicateTests: XCTestCase { ] ) XCTAssert(predicate == expected) - + let predicateString = String(data: try! encoder.encode(predicate), encoding: .utf8)! let expectedString = String(data: try! encoder.encode(expected), encoding: .utf8)! XCTAssert(predicateString == expectedString) @@ -163,7 +163,7 @@ class QueryPredicateTests: XCTestCase { && !(post.updatedAt == nil) XCTAssertEqual(funcationPredicate, operatorPredicate) - + let funcationPredicateString = String(data: try! encoder.encode(funcationPredicate), encoding: .utf8)! let operatorPredicateString = String(data: try! encoder.encode(operatorPredicate), encoding: .utf8)! XCTAssert(funcationPredicateString == operatorPredicateString) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLStatementTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLStatementTests.swift index 19806595c8..1d3b7318ee 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLStatementTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLStatementTests.swift @@ -289,10 +289,12 @@ class SQLStatementTests: XCTestCase { /// - check if the generated SQL statement is valid /// - check if the variables match the expected values func testInsertStatementFromModel() { - let post = Post(title: "title", - content: "content", - createdAt: .now(), - status: .draft) + let post = Post( + title: "title", + content: "content", + createdAt: .now(), + status: .draft + ) let statement = InsertStatement(model: post, modelSchema: post.schema) let expectedStatement = """ @@ -317,9 +319,11 @@ class SQLStatementTests: XCTestCase { let modelId = "the-id" let dob = Temporal.DateTime.now() - let model = ModelCompositePk(id: modelId, - dob: dob, - name: "the-name") + let model = ModelCompositePk( + id: modelId, + dob: dob, + name: "the-name" + ) let statement = InsertStatement(model: model, modelSchema: model.schema) let expectedStatement = """ @@ -368,13 +372,17 @@ class SQLStatementTests: XCTestCase { /// - check if the variables match the expected values /// - check if the foreign key matches `ModelCompositePkWithAssociation` PK func testInsertStatementModelWithCompositeKeyAndHasManyBidirectional() { - let parentModel = ModelCompositePkWithAssociation(id: "parent-id", - dob: .now(), - name: "parent-name") - let childModel = ModelCompositePkBelongsTo(id: "child-id", - dob: .now(), - name: "child-name", - owner: parentModel) + let parentModel = ModelCompositePkWithAssociation( + id: "parent-id", + dob: .now(), + name: "parent-name" + ) + let childModel = ModelCompositePkBelongsTo( + id: "child-id", + dob: .now(), + name: "child-name", + owner: parentModel + ) let statement = InsertStatement(model: childModel, modelSchema: childModel.schema) @@ -402,9 +410,11 @@ class SQLStatementTests: XCTestCase { /// - check if the foreign key matches `PostWithCompositeKey` PK func testInsertStatementModelWithCompositeKeyAndHasManyBidirectional2() { let parentModel = PostWithCompositeKey(id: "post-id", title: "post-title") - let childModel = CommentWithCompositeKey(id: "comment-id", - content: "content", - post: parentModel) + let childModel = CommentWithCompositeKey( + id: "comment-id", + content: "content", + post: parentModel + ) let statement = InsertStatement(model: childModel, modelSchema: childModel.schema) @@ -494,9 +504,11 @@ class SQLStatementTests: XCTestCase { func testUpdateStatementFromModelWithDefinedCustomPK() { let modelId = "the-id" let dob = Temporal.DateTime.now() - let model = ModelCustomPkDefined(id: modelId, - dob: dob, - name: "the-name") + let model = ModelCustomPkDefined( + id: modelId, + dob: dob, + name: "the-name" + ) let statement = UpdateStatement(model: model, modelSchema: model.schema) let expectedStatement = """ update "ModelCustomPkDefined" @@ -526,9 +538,11 @@ class SQLStatementTests: XCTestCase { func testUpdateStatementFromModelWithCustomPKBasedOnIndexes() { let modelId = "the-id" let dob = Temporal.DateTime.now() - let model = ModelCompositePk(id: modelId, - dob: dob, - name: "the-name") + let model = ModelCompositePk( + id: modelId, + dob: dob, + name: "the-name" + ) let statement = UpdateStatement(model: model, modelSchema: model.schema) let expectedStatement = """ update "ModelCompositePk" @@ -559,9 +573,11 @@ class SQLStatementTests: XCTestCase { /// - check if the variables match the expected values func testDeleteStatementFromModel() { let id = UUID().uuidString - let statement = DeleteStatement(Post.self, - modelSchema: Post.schema, - withId: id) + let statement = DeleteStatement( + Post.self, + modelSchema: Post.schema, + withId: id + ) let expectedStatement = """ delete from "Post" as root @@ -582,10 +598,12 @@ class SQLStatementTests: XCTestCase { /// - check if the variables match the expected values func testDeleteStatementFromModelWithCondition() { let id = UUID().uuidString - let statement = DeleteStatement(Post.self, - modelSchema: Post.schema, - withId: id, - predicate: Post.keys.content == "content") + let statement = DeleteStatement( + Post.self, + modelSchema: Post.schema, + withId: id, + predicate: Post.keys.content == "content" + ) let expectedStatement = """ delete from "Post" as root @@ -610,8 +628,10 @@ class SQLStatementTests: XCTestCase { /// - check if the variables match the expected values func testDeleteStatementFromModelWithCustomPK() { let identifier = ModelExplicitCustomPk.IdentifierProtocol.identifier(userId: "userId") - let statement = DeleteStatement(modelSchema: ModelExplicitCustomPk.schema, - withIdentifier: identifier) + let statement = DeleteStatement( + modelSchema: ModelExplicitCustomPk.schema, + withIdentifier: identifier + ) let expectedStatement = """ delete from "ModelExplicitCustomPk" as root @@ -631,10 +651,14 @@ class SQLStatementTests: XCTestCase { /// - check if the generated SQL statement is valid /// - check if the variables match the expected values func testDeleteStatementFromModelWithCompositePK() { - let identifier = ModelCompositePk.IdentifierProtocol.identifier(id: "id", - dob: Temporal.DateTime.now()) - let statement = DeleteStatement(modelSchema: ModelCompositePk.schema, - withIdentifier: identifier) + let identifier = ModelCompositePk.IdentifierProtocol.identifier( + id: "id", + dob: Temporal.DateTime.now() + ) + let statement = DeleteStatement( + modelSchema: ModelCompositePk.schema, + withIdentifier: identifier + ) let expectedStatement = """ delete from "ModelCompositePk" as root @@ -721,8 +745,10 @@ class SQLStatementTests: XCTestCase { let keys = ModelCompositePk.keys let modelId = "an-id" let dob = "2022-02-22" - let statement = SelectStatement(from: ModelCompositePk.schema, - predicate: keys.id == modelId && keys.dob == dob) + let statement = SelectStatement( + from: ModelCompositePk.schema, + predicate: keys.id == modelId && keys.dob == dob + ) let expectedStatement = """ select "root"."@@primaryKey" as "@@primaryKey", "root"."id" as "id", "root"."dob" as "dob", @@ -857,8 +883,10 @@ class SQLStatementTests: XCTestCase { func testSelectStatementWithTwoFieldsSort() { let ascSort = QuerySortDescriptor(fieldName: Post.keys.id.stringValue, order: .ascending) let dscSort = QuerySortDescriptor(fieldName: Post.keys.createdAt.stringValue, order: .descending) - let statement = SelectStatement(from: Post.schema, - sort: [ascSort, dscSort]) + let statement = SelectStatement( + from: Post.schema, + sort: [ascSort, dscSort] + ) let expectedStatement = """ select "root"."id" as "id", "root"."content" as "content", "root"."createdAt" as "createdAt", @@ -879,9 +907,11 @@ class SQLStatementTests: XCTestCase { /// - check if the statement contains the correct `where` statement, `order by` and `ascending` func testSelectStatementWithPredicateAndSort() { let sort = QuerySortDescriptor(fieldName: Post.keys.id.stringValue, order: .descending) - let statement = SelectStatement(from: Post.schema, - predicate: Post.keys.rating > 4, - sort: [sort]) + let statement = SelectStatement( + from: Post.schema, + predicate: Post.keys.rating > 4, + sort: [sort] + ) let expectedStatement = """ select "root"."id" as "id", "root"."content" as "content", "root"."createdAt" as "createdAt", @@ -905,9 +935,11 @@ class SQLStatementTests: XCTestCase { /// - check if the statement contains the correct `where` statement, `order by` and `ascending` func testSelectStatementWithSortAndPaginationInfo() { let sort = QuerySortDescriptor(fieldName: Post.keys.id.stringValue, order: .descending) - let statement = SelectStatement(from: Post.schema, - sort: [sort], - paginationInput: .page(0, limit: 5)) + let statement = SelectStatement( + from: Post.schema, + sort: [sort], + paginationInput: .page(0, limit: 5) + ) let expectedStatement = """ select "root"."id" as "id", "root"."content" as "content", "root"."createdAt" as "createdAt", @@ -931,10 +963,12 @@ class SQLStatementTests: XCTestCase { /// - check if the statement contains the correct `where` statement, `order by` and `ascending` func testSelectStatementWithPredicateAndSortAndPaginationInfo() { let sort = QuerySortDescriptor(fieldName: Post.keys.id.stringValue, order: .descending) - let statement = SelectStatement(from: Post.schema, - predicate: Post.keys.rating > 4, - sort: [sort], - paginationInput: .page(0, limit: 5)) + let statement = SelectStatement( + from: Post.schema, + predicate: Post.keys.rating > 4, + sort: [sort], + paginationInput: .page(0, limit: 5) + ) let expectedStatement = """ select "root"."id" as "id", "root"."content" as "content", "root"."createdAt" as "createdAt", @@ -1023,15 +1057,17 @@ class SQLStatementTests: XCTestCase { /// - it matches the SQL condition func testTranslateQueryPredicateOperations() { - func assertPredicate(_ predicate: QueryPredicate, - matches sql: String, - bindings: [Binding?]? = nil) { + func assertPredicate( + _ predicate: QueryPredicate, + matches sql: String, + bindings: [Binding?]? = nil + ) { let statement = ConditionStatement(modelSchema: Post.schema, predicate: predicate, namespace: "root") XCTAssertEqual(statement.stringValue, " and \(sql)") - if let bindings = bindings { + if let bindings { XCTAssertEqual(bindings.count, statement.variables.count) - bindings.enumerated().forEach { - if let one = $0.element, let other = statement.variables[$0.offset] { + for binding in bindings.enumerated() { + if let one = binding.element, let other = statement.variables[binding.offset] { // TODO find better way to test `Binding` equality XCTAssertEqual(String(describing: one), String(describing: other)) } @@ -1048,15 +1084,21 @@ class SQLStatementTests: XCTestCase { assertPredicate(post.rating >= 1, matches: "\"root\".\"rating\" >= ?", bindings: [1]) assertPredicate(post.rating < 2, matches: "\"root\".\"rating\" < ?", bindings: [2]) assertPredicate(post.rating <= 3, matches: "\"root\".\"rating\" <= ?", bindings: [3]) - assertPredicate(post.rating.between(start: 3, end: 5), - matches: "\"root\".\"rating\" between ? and ?", - bindings: [3, 5]) - assertPredicate(post.title.beginsWith("gelato"), - matches: "instr(\"root\".\"title\", ?) = 1", - bindings: ["gelato"]) - assertPredicate(post.title ~= "gelato", - matches: "instr(\"root\".\"title\", ?) > 0", - bindings: ["gelato"]) + assertPredicate( + post.rating.between(start: 3, end: 5), + matches: "\"root\".\"rating\" between ? and ?", + bindings: [3, 5] + ) + assertPredicate( + post.title.beginsWith("gelato"), + matches: "instr(\"root\".\"title\", ?) = 1", + bindings: ["gelato"] + ) + assertPredicate( + post.title ~= "gelato", + matches: "instr(\"root\".\"title\", ?) > 0", + bindings: ["gelato"] + ) } /// - Given: a grouped predicate diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift index 7db19c714d..fbc11605bc 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift @@ -35,13 +35,17 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - let syncEngine = try RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault()) - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let syncEngine = try RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault() + ) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -50,11 +54,13 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { return self.storageEngine } let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestJsonModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestJsonModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true @@ -77,16 +83,18 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - Then: /// - call `query(Post)` to check if the model was correctly inserted func testInsertPost() async { - let expectation = self.expectation( + let expectation = expectation( description: "it should save and select a Post from the database") // insert a post let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) storageAdapter.save(model, modelSchema: ModelRegistry.modelSchema(from: "Post")!) { saveResult in @@ -94,7 +102,8 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { case .success: self.storageAdapter.query( DynamicModel.self, - modelSchema: ModelRegistry.modelSchema(from: "Post")!) { queryResult in + modelSchema: ModelRegistry.modelSchema(from: "Post")! + ) { queryResult in switch queryResult { case .success(let posts): XCTAssert(posts.count == 1) @@ -125,7 +134,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - call `query(Post, where: title == post.title)` to check /// if the model was correctly inserted using a predicate func testInsertPostAndSelectByTitle() async { - let expectation = self.expectation( + let expectation = expectation( description: "it should save and select a Post from the database") // insert a post @@ -133,9 +142,11 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) storageAdapter.save(model, modelSchema: ModelRegistry.modelSchema(from: "Post")!) { saveResult in switch saveResult { @@ -174,16 +185,18 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - check if the `query(Post)` returns only 1 post /// - the post has the updated title func testInsertPostAndThenUpdateIt() async { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and update a Post") // insert a post let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) func checkSavedPost(id: String) { @@ -206,9 +219,11 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { storageAdapter.save(model, modelSchema: ModelRegistry.modelSchema(from: "Post")!) { insertResult in switch insertResult { case .success: - let updatedPost = ["title": .string("title updated"), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let updatedPost = [ + "title": .string("title updated"), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(id: model.id, values: updatedPost) self.storageAdapter.save(model, modelSchema: ModelRegistry.modelSchema(from: "Post")!) { updateResult in switch updateResult { @@ -242,20 +257,24 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let schema = ModelRegistry.modelSchema(from: "Post")! - + storageAdapter.save(model, modelSchema: schema) { insertResult in switch insertResult { case .success: saveExpectation.fulfill() - self.storageAdapter.delete(DynamicModel.self, - modelSchema: schema, - withIdentifier: model.identifier(schema: schema), - condition: nil) { + self.storageAdapter.delete( + DynamicModel.self, + modelSchema: schema, + withIdentifier: model.identifier(schema: schema), + condition: nil + ) { switch $0 { case .success: deleteExpectation.fulfill() @@ -281,7 +300,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - a successful update for `update(post, condition)` /// - call `query(Post)` to check if the model was correctly updated func testInsertPostAndThenUpdateItWithCondition() { - let expectation = self.expectation(description: "it should insert and update a Post") + let expectation = expectation(description: "it should insert and update a Post") let schema = ModelRegistry.modelSchema(from: "Post")! func checkSavedPost(id: String) { storageAdapter.query(DynamicModel.self, modelSchema: schema) { @@ -304,17 +323,21 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) storageAdapter.save(model, modelSchema: schema) { insertResult in switch insertResult { case .success: - let updatedPost = ["title": .string("title updated"), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let updatedPost = [ + "title": .string("title updated"), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let updatedModel = DynamicModel(id: model.id, values: updatedPost) let condition = QueryPredicateOperation(field: "content", operator: .equals(content)) self.storageAdapter.save(updatedModel, modelSchema: schema, condition: condition) { updateResult in @@ -339,16 +362,18 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - Then: /// - Fails with conditional save failed error when there is no existing model instance func testUpdateWithConditionFailsWhenNoExistingModel() { - let expectation = self.expectation( + let expectation = expectation( description: "it should fail to update the Post that does not exist") // insert a post let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let schema = ModelRegistry.modelSchema(from: "Post")! let condition = QueryPredicateOperation(field: "content", operator: .equals(content)) @@ -376,31 +401,39 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { /// - call `update(post, condition)` with `post.title` updated and condition does not match /// - the update for `update(post, condition)` fails with conditional save failed error func testInsertPostAndThenUpdateItWithConditionDoesNotMatchShouldReturnError() { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and then fail to update the Post, given bad condition") // insert a post let title = "title not updated" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let schema = ModelRegistry.modelSchema(from: "Post")! storageAdapter.save(model, modelSchema: schema) { insertResult in switch insertResult { case .success: - let updatedPost = ["title": .string("title updated"), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let updatedPost = [ + "title": .string("title updated"), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let updatedModel = DynamicModel(id: model.id, values: updatedPost) - let condition = QueryPredicateOperation(field: "content", - operator: .equals("content 2 does not match previous content")) - self.storageAdapter.save(updatedModel, - modelSchema: schema, - condition: condition) { updateResult in + let condition = QueryPredicateOperation( + field: "content", + operator: .equals("content 2 does not match previous content") + ) + self.storageAdapter.save( + updatedModel, + modelSchema: schema, + condition: condition + ) { updateResult in switch updateResult { case .success: XCTFail("Update should not be successful") @@ -432,9 +465,11 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { let title = "title1" let content = "content1" let createdAt = dateInFuture.iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let schema = ModelRegistry.modelSchema(from: "Post")! @@ -442,11 +477,15 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { switch insertResult { case .success: saveExpectation.fulfill() - let predicate = QueryPredicateOperation(field: "createdAt", - operator: .greaterThan(dateTestStart.iso8601String)) - self.storageAdapter.delete(DynamicModel.self, - modelSchema: Post.schema, - filter: predicate) { result in + let predicate = QueryPredicateOperation( + field: "createdAt", + operator: .greaterThan(dateTestStart.iso8601String) + ) + self.storageAdapter.delete( + DynamicModel.self, + modelSchema: Post.schema, + filter: predicate + ) { result in switch result { case .success: deleteExpectation.fulfill() @@ -479,9 +518,11 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { let title = "\(titleX)\(counter)" let content = "\(contentX)\(counter)" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) storageAdapter.save(model, modelSchema: schema) { insertResult in @@ -490,9 +531,11 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { postsAdded.append(model.id) if counter == maxCount - 1 { saveExpectation.fulfill() - self.storageAdapter.delete(DynamicModel.self, - modelSchema: schema, - filter: QueryPredicateConstant.all) { result in + self.storageAdapter.delete( + DynamicModel.self, + modelSchema: schema, + filter: QueryPredicateConstant.all + ) { result in switch result { case .success: deleteExpectation.fulfill() diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift index c14e909701..7d4de9d3f9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite import SQLite3 +import XCTest @testable import Amplify -@testable import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import AWSPluginsCore // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -24,7 +24,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - Then: /// - call `query(Post)` to check if the model was correctly inserted func testInsertPost() { - let expectation = self.expectation( + let expectation = expectation( description: "it should save and select a Post from the database") // insert a post @@ -63,7 +63,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - Then: /// - call `query(Post)` to check if the model was correctly inserted func testInsertPostWithAll() { - let expectation = self.expectation( + let expectation = expectation( description: "it should save and select a Post from the database") // insert a post @@ -103,7 +103,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - call `query(Post, where: title == post.title)` to check /// if the model was correctly inserted using a predicate func testInsertPostAndSelectByTitle() { - let expectation = self.expectation( + let expectation = expectation( description: "it should save and select a Post from the database") // insert a post @@ -145,7 +145,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - check if the `query(Post)` returns only 1 post /// - the post has the updated title func testInsertPostAndThenUpdateIt() { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and update a Post") func checkSavedPost(id: String) { @@ -195,7 +195,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - a successful update for `update(post, condition)` /// - call `query(Post)` to check if the model was correctly updated func testInsertPostAndThenUpdateItWithCondition() { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and update a Post") func checkSavedPost(id: String) { @@ -245,7 +245,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - a successful update for `update(post, condition)` /// - call `query(Post)` to check if the model was correctly updated func testInsertPostAndThenUpdateItWithConditionAll() { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and update a Post") func checkSavedPost(id: String) { @@ -292,7 +292,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - Then: /// - Fails with conditional save failed error when there is no existing model instance func testUpdateWithConditionFailsWhenNoExistingModel() { - let expectation = self.expectation( + let expectation = expectation( description: "it should fail to update the Post that does not exist") let post = Post(title: "title", content: "content", createdAt: .now()) @@ -321,7 +321,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { /// - call `update(post, condition)` with `post.title` updated and condition does not match /// - the update for `update(post, condition)` fails with conditional save failed error func testInsertPostAndThenUpdateItWithConditionDoesNotMatchShouldReturnError() { - let expectation = self.expectation( + let expectation = expectation( description: "it should insert and then fail to update the Post, given bad condition") var post = Post(title: "title not updated", content: "content", createdAt: .now()) @@ -367,9 +367,11 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { switch insertResult { case .success: saveExpectation.fulfill() - self.storageAdapter.delete(untypedModelType: Post.self, - modelSchema: Post.schema, - withIdentifier: post.identifier(schema: Post.schema)) { + self.storageAdapter.delete( + untypedModelType: Post.self, + modelSchema: Post.schema, + withIdentifier: post.identifier(schema: Post.schema) + ) { switch $0 { case .success: deleteExpectation.fulfill() @@ -401,10 +403,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { saveExpectation.fulfill() let postKeys = Post.keys let predicate = postKeys.createdAt.gt(dateTestStart) - self.storageAdapter.delete(Post.self, - modelSchema: Post.schema, - withIdentifier: post.identifier(schema: Post.schema), - condition: predicate) { result in + self.storageAdapter.delete( + Post.self, + modelSchema: Post.schema, + withIdentifier: post.identifier(schema: Post.schema), + condition: predicate + ) { result in switch result { case .success: deleteExpectation.fulfill() @@ -436,10 +440,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { saveExpectation.fulfill() let postKeys = Post.keys let predicate = postKeys.createdAt.lt(dateTestStart) - self.storageAdapter.delete(Post.self, - modelSchema: Post.schema, - withIdentifier: post.identifier(schema: Post.schema), - condition: predicate) { result in + self.storageAdapter.delete( + Post.self, + modelSchema: Post.schema, + withIdentifier: post.identifier(schema: Post.schema), + condition: predicate + ) { result in switch result { case .success: deleteCompleteExpectation.fulfill() @@ -510,9 +516,11 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { postsAdded.append(post.id) if counter == maxCount - 1 { saveExpectation.fulfill() - self.storageAdapter.delete(Post.self, - modelSchema: Post.schema, - filter: QueryPredicateConstant.all) { result in + self.storageAdapter.delete( + Post.self, + modelSchema: Post.schema, + filter: QueryPredicateConstant.all + ) { result in switch result { case .success: deleteExpectation.fulfill() @@ -566,10 +574,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } do { - _ = try SQLiteStorageEngineAdapter.clearIfNewVersion(version: newVersion, - dbFilePath: URL(string: "dbFilePath")!, - userDefaults: userDefaults, - fileManager: mockFileManager) + _ = try SQLiteStorageEngineAdapter.clearIfNewVersion( + version: newVersion, + dbFilePath: URL(string: "dbFilePath")!, + userDefaults: userDefaults, + fileManager: mockFileManager + ) } catch { XCTFail("Test failed due to \(error)") } @@ -593,10 +603,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } do { - _ = try SQLiteStorageEngineAdapter.clearIfNewVersion(version: newVersion, - dbFilePath: URL(string: "dbFilePath")!, - userDefaults: userDefaults, - fileManager: mockFileManager) + _ = try SQLiteStorageEngineAdapter.clearIfNewVersion( + version: newVersion, + dbFilePath: URL(string: "dbFilePath")!, + userDefaults: userDefaults, + fileManager: mockFileManager + ) } catch { XCTFail("Test failed due to \(error)") } @@ -620,10 +632,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } do { - _ = try SQLiteStorageEngineAdapter.clearIfNewVersion(version: newVersion, - dbFilePath: URL(string: "dbFilePath")!, - userDefaults: userDefaults, - fileManager: mockFileManager) + _ = try SQLiteStorageEngineAdapter.clearIfNewVersion( + version: newVersion, + dbFilePath: URL(string: "dbFilePath")!, + userDefaults: userDefaults, + fileManager: mockFileManager + ) } catch { XCTFail("Test failed due to \(error)") } @@ -645,10 +659,12 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { mockFileManager.fileExists = true do { - _ = try SQLiteStorageEngineAdapter.clearIfNewVersion(version: newVersion, - dbFilePath: URL(string: "dbFilePath")!, - userDefaults: userDefaults, - fileManager: mockFileManager) + _ = try SQLiteStorageEngineAdapter.clearIfNewVersion( + version: newVersion, + dbFilePath: URL(string: "dbFilePath")!, + userDefaults: userDefaults, + fileManager: mockFileManager + ) } catch { guard let dataStoreError = error as? DataStoreError, case .invalidDatabase = dataStoreError else { XCTFail("Expected DataStoreErrorF") @@ -673,11 +689,13 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { let querySuccess = expectation(description: "query for metadata success") let modelId = UUID().uuidString let modelName = "modelName" - let metadata = MutationSyncMetadata(modelId: modelId, - modelName: modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let metadata = MutationSyncMetadata( + modelId: modelId, + modelName: modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) storageAdapter.save(metadata) { result in switch result { @@ -697,16 +715,20 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { func testQueryMutationSyncMetadataForModelIds() { let modelName = "modelName" - let metadata1 = MutationSyncMetadata(modelId: UUID().uuidString, - modelName: modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) - let metadata2 = MutationSyncMetadata(modelId: UUID().uuidString, - modelName: modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let metadata1 = MutationSyncMetadata( + modelId: UUID().uuidString, + modelName: modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) + let metadata2 = MutationSyncMetadata( + modelId: UUID().uuidString, + modelName: modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let saveMetadata1 = expectation(description: "save metadata1 success") storageAdapter.save(metadata1) { result in @@ -744,18 +766,22 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } func testShouldIgnoreConstraintViolationError() { - let constraintViolationError = Result.error(message: "Foreign Key Constraint Violation", - code: SQLITE_CONSTRAINT, - statement: nil) + let constraintViolationError = Result.error( + message: "Foreign Key Constraint Violation", + code: SQLITE_CONSTRAINT, + statement: nil + ) let dataStoreError = DataStoreError.invalidOperation(causedBy: constraintViolationError) XCTAssertTrue(storageAdapter.shouldIgnoreError(error: dataStoreError)) } func testShouldIgnoreErrorFalse() { - let constraintViolationError = Result.error(message: "", - code: SQLITE_BUSY, - statement: nil) + let constraintViolationError = Result.error( + message: "", + code: SQLITE_BUSY, + statement: nil + ) let dataStoreError = DataStoreError.invalidOperation(causedBy: constraintViolationError) XCTAssertFalse(storageAdapter.shouldIgnoreError(error: dataStoreError)) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SortByDependencyOrderTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SortByDependencyOrderTests.swift index 8cf43905af..3d7950a46a 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SortByDependencyOrderTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SortByDependencyOrderTests.swift @@ -39,7 +39,7 @@ class SortByDependencyOrderTests: XCTestCase { let sorted = modelSchemas.sortByDependencyOrder() - let sortedModelNames = sorted.map { $0.name } + let sortedModelNames = sorted.map(\.name) XCTAssertEqual(sortedModelNames, ["Post", "Comment"]) } @@ -53,7 +53,7 @@ class SortByDependencyOrderTests: XCTestCase { let sorted = modelSchemas.sortByDependencyOrder() - let sortedModelNames = sorted.map { $0.name } + let sortedModelNames = sorted.map(\.name) XCTAssertEqual(sortedModelNames, ["Post", "Comment", "MockSynced"]) } @@ -67,7 +67,7 @@ class SortByDependencyOrderTests: XCTestCase { let sorted = modelSchemas.sortByDependencyOrder() - let sortedModelNames = sorted.map { $0.name } + let sortedModelNames = sorted.map(\.name) XCTAssertEqual(sortedModelNames, ["Post", "Comment", "UserAccount", "UserProfile"]) } @@ -81,7 +81,7 @@ class SortByDependencyOrderTests: XCTestCase { let sorted = modelSchemas.sortByDependencyOrder() - let sortedModelNames = sorted.map { $0.name } + let sortedModelNames = sorted.map(\.name) XCTAssertEqual(sortedModelNames, ["Author", "Book", "BookAuthor"]) } @@ -91,15 +91,23 @@ class SortByDependencyOrderTests: XCTestCase { /// - Then: /// - the ordered list is deterministically sorted, although not necessarily predictable func testSortsDeterministically() { - let expectedModelNames = ["Author", "Book", "BookAuthor", "Post", "Comment", "MockUnsynced", - "UserAccount", "UserProfile"] + let expectedModelNames = [ + "Author", + "Book", + "BookAuthor", + "Post", + "Comment", + "MockUnsynced", + "UserAccount", + "UserProfile" + ] for _ in 0 ..< 10 { - let modelSchemas = modelList.shuffled().map { (modelType) -> ModelSchema in + let modelSchemas = modelList.shuffled().map { modelType -> ModelSchema in modelType.schema } let sorted = modelSchemas.sortByDependencyOrder() - let sortedModelNames = sorted.map { $0.name } + let sortedModelNames = sorted.map(\.name) XCTAssertEqual(sortedModelNames, expectedModelNames) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift index 5d36c0ca33..9ec1dfebc1 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Combine +import XCTest // Testable import b/c StateMachine is an internal type @testable import AWSDataStorePlugin @@ -106,12 +106,16 @@ class StateMachineTests: XCTestCase { } } - await fulfillment(of: [receivedOneOnSubscribe, - receivedTwoAfterSubscribe, - receivedThreeAfterSubscribe, - receivedOneAfterSubscribe], - timeout: 1, - enforceOrder: true) + await fulfillment( + of: [ + receivedOneOnSubscribe, + receivedTwoAfterSubscribe, + receivedThreeAfterSubscribe, + receivedOneAfterSubscribe + ], + timeout: 1, + enforceOrder: true + ) listener.cancel() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift index 07c9e922b2..557671017e 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class StorageAdapterMutationSyncTests: BaseDataStoreTests { @@ -29,19 +29,21 @@ class StorageAdapterMutationSyncTests: BaseDataStoreTests { // then create sync metadata for them let syncMetadataList = posts.map { - MutationSyncMetadata(modelId: $0.id, - modelName: Post.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + MutationSyncMetadata( + modelId: $0.id, + modelName: Post.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) } populateData(syncMetadataList) do { let mutationSync = try storageAdapter.queryMutationSync(for: posts, modelName: Post.modelName) - mutationSync.forEach { - XCTAssertEqual($0.model.id, $0.syncMetadata.modelId) - let post = $0.model.instance as? Post + for item in mutationSync { + XCTAssertEqual(item.model.id, item.syncMetadata.modelId) + let post = item.model.instance as? Post XCTAssertNotNil(post) } expect.fulfill() diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MockMutationSyncMigrationDelegate.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MockMutationSyncMigrationDelegate.swift index 0b476e3669..05051f0738 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MockMutationSyncMigrationDelegate.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MockMutationSyncMigrationDelegate.swift @@ -44,14 +44,14 @@ class MockMutationSyncMetadataMigrationDelegate: MutationSyncMetadataMigrationDe func preconditionCheck() throws { stepsCalled.append(.precondition) - if let preconditionCheckError = preconditionCheckError { + if let preconditionCheckError { throw preconditionCheckError } } func transaction(_ basicClosure: () throws -> Void) throws { stepsCalled.append(.transaction) - if let transactionError = transactionError { + if let transactionError { throw transactionError } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/ModelSyncMutationMigrationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/ModelSyncMutationMigrationTests.swift index 95e42c224a..5d7c412118 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/ModelSyncMutationMigrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/ModelSyncMutationMigrationTests.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify -@testable import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import AWSPluginsCore final class ModelSyncMetadataMigrationTests: XCTestCase { @@ -19,10 +19,10 @@ final class ModelSyncMetadataMigrationTests: XCTestCase { var storageEngine: StorageEngine! var storageAdapter: SQLiteStorageEngineAdapter! var dataStorePlugin: AWSDataStorePlugin! - + override func setUp() async throws { await Amplify.reset() - + do { connection = try Connection(.inMemory) storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) @@ -31,21 +31,22 @@ final class ModelSyncMetadataMigrationTests: XCTestCase { return } } - + /// Use the latest schema and create the table with it. /// The column should be found and no upgrade should occur. func testPerformModelMetadataSyncPredicateUpgrade_ColumnExists() throws { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) guard let field = ModelSyncMetadata.schema.field( - withName: ModelSyncMetadata.keys.syncPredicate.stringValue) else { + withName: ModelSyncMetadata.keys.syncPredicate.stringValue) + else { XCTFail("Could not find corresponding ModelField from ModelSyncMetadata for syncPredicate") return } let modelSyncMetadataMigration = ModelSyncMetadataMigration(storageAdapter: storageAdapter) - + let exists = try modelSyncMetadataMigration.columnExists(modelSchema: ModelSyncMetadata.schema, field: field) XCTAssertTrue(exists) - + do { let result = try modelSyncMetadataMigration.performModelMetadataSyncPredicateUpgrade() XCTAssertFalse(result) @@ -53,7 +54,7 @@ final class ModelSyncMetadataMigrationTests: XCTestCase { XCTFail("Failed to perform upgrade \(error)") } } - + /// Create a local copy of the previous ModelSyncMetadata, without sync predicate /// Create the table with the previous schema, and perform the upgrade. /// The upgrade should have occurred successfully. @@ -61,9 +62,11 @@ final class ModelSyncMetadataMigrationTests: XCTestCase { struct ModelSyncMetadata: Model { public let id: String public var lastSync: Int? - - public init(id: String, - lastSync: Int?) { + + public init( + id: String, + lastSync: Int? + ) { self.id = id self.lastSync = lastSync } @@ -83,14 +86,15 @@ final class ModelSyncMetadataMigrationTests: XCTestCase { try storageAdapter.setUp(modelSchemas: [ModelSyncMetadata.schema]) guard let field = AWSPluginsCore.ModelSyncMetadata.schema.field( - withName: AWSPluginsCore.ModelSyncMetadata.keys.syncPredicate.stringValue) else { + withName: AWSPluginsCore.ModelSyncMetadata.keys.syncPredicate.stringValue) + else { XCTFail("Could not find corresponding ModelField from ModelSyncMetadata for syncPredicate") return } let modelSyncMetadataMigration = ModelSyncMetadataMigration(storageAdapter: storageAdapter) let exists = try modelSyncMetadataMigration.columnExists(modelSchema: AWSPluginsCore.ModelSyncMetadata.schema, field: field) XCTAssertFalse(exists) - + do { let result = try modelSyncMetadataMigration.performModelMetadataSyncPredicateUpgrade() XCTAssertTrue(result) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift index e737a83d20..09a4512595 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -45,7 +45,7 @@ class MutationSyncMetadataMigrationTestBase: XCTestCase { // MARK: - Helpers - func save(_ model: M) { + func save(_ model: some Model) { let saveSuccess = expectation(description: "Save successful") storageAdapter.save(model) { result in switch result { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTests.swift index 51b373c436..eee67c53a9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTests.swift @@ -78,10 +78,12 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase do { try migration.apply() } catch { - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels + ]) return } @@ -97,11 +99,13 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase do { try migration.apply() } catch { - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels, - .emptyMutationSyncMetadataStore]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels, + .emptyMutationSyncMetadataStore + ]) return } XCTFail("Should catch error") @@ -116,12 +120,14 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase do { try migration.apply() } catch { - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels, - .emptyMutationSyncMetadataStore, - .emptyModelSyncMetadataStore]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels, + .emptyMutationSyncMetadataStore, + .emptyModelSyncMetadataStore + ]) return } XCTFail("Should catch error") @@ -137,11 +143,13 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase do { try migration.apply() } catch { - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels, - .removeMutationSyncMetadataCopyStore]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels, + .removeMutationSyncMetadataCopyStore + ]) return } XCTFail("Should catch error") @@ -153,15 +161,17 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase delegate.containsDuplicateIdsAcrossModelsResult = false let migration = MutationSyncMetadataMigration(delegate: delegate) try migration.apply() - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels, - .removeMutationSyncMetadataCopyStore, - .createMutationSyncMetadataCopyStore, - .backfillMutationSyncMetadata, - .removeMutationSyncMetadataStore, - .renameMutationSyncMetadataCopy]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels, + .removeMutationSyncMetadataCopyStore, + .createMutationSyncMetadataCopyStore, + .backfillMutationSyncMetadata, + .removeMutationSyncMetadataStore, + .renameMutationSyncMetadataCopy + ]) } func testApply() throws { @@ -177,8 +187,10 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase XCTAssertEqual(mutationSyncMetadatas.count, 1) XCTAssertEqual(mutationSyncMetadatas[0].id, restaurant.id) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) let migration = MutationSyncMetadataMigration(delegate: delegate) try migration.apply() @@ -193,7 +205,8 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase guard let restaurantMetadata = try storageAdapter.queryMutationSyncMetadata( for: restaurant.id, - modelName: Restaurant.modelName) else { + modelName: Restaurant.modelName + ) else { XCTFail("Could not get metadata") return } @@ -207,11 +220,13 @@ class MutationSyncMetadataMigrationTests: MutationSyncMetadataMigrationTestBase delegate.containsDuplicateIdsAcrossModelsResult = true let migration = MutationSyncMetadataMigration(delegate: delegate) try migration.apply() - XCTAssertEqual(delegate.stepsCalled, [.precondition, - .transaction, - .mutationSyncMetadataStoreEmptyOrMigrated, - .containsDuplicateIdsAcrossModels, - .emptyMutationSyncMetadataStore, - .emptyModelSyncMetadataStore]) + XCTAssertEqual(delegate.stepsCalled, [ + .precondition, + .transaction, + .mutationSyncMetadataStoreEmptyOrMigrated, + .containsDuplicateIdsAcrossModels, + .emptyMutationSyncMetadataStore, + .emptyModelSyncMetadataStore + ]) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationDelegateTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationDelegateTests.swift index 68667e65e8..4570ec20e9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationDelegateTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationDelegateTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -19,8 +19,10 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr func testClearSuccess() throws { try setUpAllModels() - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) try delegate.emptyMutationSyncMetadataStore() try delegate.emptyModelSyncMetadataStore() } @@ -36,8 +38,10 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr } XCTAssertEqual(mutationSyncMetadatas.count, 1) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) let sql = try delegate.emptyMutationSyncMetadataStore() XCTAssertEqual(sql, "delete from \"MutationSyncMetadata\" as root") guard let mutationSyncMetadatas = queryMutationSyncMetadata() else { @@ -58,8 +62,10 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr } XCTAssertEqual(modelSyncMetadatas.count, 1) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) let sql = try delegate.emptyModelSyncMetadataStore() XCTAssertEqual(sql, "delete from \"ModelSyncMetadata\" as root") guard let modelSyncMetadatasDeleted = queryModelSyncMetadata() else { @@ -84,8 +90,10 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr XCTAssertEqual(mutationSyncMetadatas.count, 1) XCTAssertEqual(mutationSyncMetadatas[0].id, restaurant.id) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) try delegate.removeMutationSyncMetadataCopyStore() try delegate.createMutationSyncMetadataCopyStore() @@ -103,7 +111,8 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr guard let restaurantMetadata = try storageAdapter.queryMutationSyncMetadata( for: restaurant.id, - modelName: Restaurant.modelName) else { + modelName: Restaurant.modelName + ) else { XCTFail("Could not get metadata") return } @@ -113,8 +122,10 @@ class SQLiteMutationSyncMetadataMigrationDelegateTests: MutationSyncMetadataMigr /// Ensure creating and dropping the MutationSyncMetadataCopy works as expected func testDropMutationSyncMetadataCopyIfExists() throws { - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) try delegate.removeMutationSyncMetadataCopyStore() // Dropping the table without the table in the database is successful diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift index d259ddf91d..1f451a37c0 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift @@ -5,21 +5,23 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest +import SQLite3 @testable import Amplify @testable import AmplifyTestCommon @testable import AWSDataStorePlugin @testable import AWSPluginsCore -import SQLite3 class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMigrationTestBase { // MARK: - Precondition tests func testPreconditionSuccess() throws { - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) try delegate.preconditionCheck() } @@ -28,8 +30,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi func testSelectMutationSyncMetadataWithoutTableShouldThrow() { let shouldCatchFailure = expectation(description: "select MutationSyncMetadata without table should fail") do { - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) _ = try delegate.selectMutationSyncMetadataRecords() } catch { guard let resultError = error as? Result, @@ -50,8 +54,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi try setUpAllModels() let metadata = MutationSyncMetadata(id: UUID().uuidString, deleted: false, lastChangedAt: 1, version: 1) save(metadata) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) XCTAssertFalse(try delegate.mutationSyncMetadataStoreEmptyOrMigrated()) } @@ -59,14 +65,18 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi /// Set up MutationSyncMetadata records where the id is in the correct format. Check that it does not need migration func testMutationSyncMetadataStoreNotEmptyAndMigrated() throws { try setUpAllModels() - let metadata = MutationSyncMetadata(modelId: UUID().uuidString, - modelName: "modelName", - deleted: false, - lastChangedAt: 1, - version: 1) + let metadata = MutationSyncMetadata( + modelId: UUID().uuidString, + modelName: "modelName", + deleted: false, + lastChangedAt: 1, + version: 1 + ) save(metadata) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) XCTAssertTrue(try delegate.mutationSyncMetadataStoreEmptyOrMigrated()) } @@ -75,8 +85,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi func testSelectDuplicateIdCountAcrossModelsWithoutTableShouldThrow() { let shouldCatchFailure = expectation(description: "select duplicate id count without model tables should fail") - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) do { _ = try delegate.containsDuplicateIdsAcrossModels() } catch { @@ -95,8 +107,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi func testSelectDuplicateIdAcrossModelsStatement() throws { try setUpAllModels() - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) let expected = "SELECT id, tableName, count(id) as count FROM " + "(SELECT id, 'Restaurant' as tableName FROM Restaurant UNION ALL " + "SELECT id, 'Menu' as tableName FROM Menu UNION ALL " + @@ -106,8 +120,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi func testSelectDuplicateIdCountAcrossModels_NoData() throws { try setUpAllModels() - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) XCTAssertFalse(try delegate.containsDuplicateIdsAcrossModels()) } @@ -119,8 +135,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi save(menu) let dish = Dish(dishName: "name", menu: menu) save(dish) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) XCTAssertFalse(try delegate.containsDuplicateIdsAcrossModels()) } @@ -134,8 +152,10 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi save(menu) let dish = Dish(id: "1", dishName: "name", menu: menu) save(dish) - let delegate = SQLiteMutationSyncMetadataMigrationDelegate(storageAdapter: storageAdapter, - modelSchemas: modelSchemas) + let delegate = SQLiteMutationSyncMetadataMigrationDelegate( + storageAdapter: storageAdapter, + modelSchemas: modelSchemas + ) XCTAssertTrue(try delegate.containsDuplicateIdsAcrossModels()) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/DynamicModel.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/DynamicModel.swift index f423694eff..9109fead18 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/DynamicModel.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/DynamicModel.swift @@ -13,8 +13,10 @@ struct DynamicModel: Model, JSONValueHolder { public let id: String public var values: [String: JSONValue] - public init(id: String = UUID().uuidString, - values: [String: JSONValue]) { + public init( + id: String = UUID().uuidString, + values: [String: JSONValue] + ) { self.id = id var valueWIthId = values valueWIthId["id"] = .string(id) @@ -23,8 +25,8 @@ struct DynamicModel: Model, JSONValueHolder { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - id = try container.decode(String.self, forKey: .id) - values = try decoder.singleValueContainer().decode([String: JSONValue].self) + self.id = try container.decode(String.self, forKey: .id) + self.values = try decoder.singleValueContainer().decode([String: JSONValue].self) } public func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/ExampleWithEveryType+Schema.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/ExampleWithEveryType+Schema.swift index 3d4f7276ba..361f2b4c12 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/ExampleWithEveryType+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/ExampleWithEveryType+Schema.swift @@ -8,11 +8,11 @@ import Amplify import Foundation -extension ExampleWithEveryType { +public extension ExampleWithEveryType { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case stringField case intField @@ -24,11 +24,11 @@ extension ExampleWithEveryType { case arrayOfStringsField } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let example = ExampleWithEveryType.keys model.listPluralName = "ExampleWithEveryTypes" diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/SQLModelValueConverterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/SQLModelValueConverterTests.swift index ac65ccd105..b3a1881469 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/SQLModelValueConverterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Models/SQLModelValueConverterTests.swift @@ -8,10 +8,10 @@ import Foundation import XCTest +import AmplifyTestCommon @testable import Amplify @testable import AWSDataStorePlugin @testable import SQLite -import AmplifyTestCommon class SQLModelValueConverterTests: BaseDataStoreTests { @@ -29,15 +29,17 @@ class SQLModelValueConverterTests: BaseDataStoreTests { let nonModelExample = ExampleNonModelType(someString: "string", someEnum: .foo) // example model - let example = ExampleWithEveryType(id: testId, - stringField: "string", - intField: 20, - doubleField: 6.5, - boolField: true, - dateField: testDate, - enumField: .bar, - nonModelField: nonModelExample, - arrayOfStringsField: ["foo", "bar"]) + let example = ExampleWithEveryType( + id: testId, + stringField: "string", + intField: 20, + doubleField: 6.5, + boolField: true, + dateField: testDate, + enumField: .bar, + nonModelField: nonModelExample, + arrayOfStringsField: ["foo", "bar"] + ) return example } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift index f7eea5c6aa..092fb1e95a 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import SQLite import Combine +import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -28,11 +28,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: Restaurant.self) ModelRegistry.register(modelType: Menu.self) ModelRegistry.register(modelType: Dish.self) @@ -65,19 +67,23 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { return } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id - guard case .success(let queriedRestaurants) = await queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = await queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } XCTAssertEqual(queriedRestaurants.count, 1) let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier + ) { result in switch result { case .success(let restaurant): XCTAssertNotNil(restaurant) @@ -88,8 +94,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() await fulfillment(of: [completed], timeout: 1) - guard case .success(let queriedRestaurants) = await queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = await queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -106,8 +114,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = ModelCompositePk.keys.id == modelId && ModelCompositePk.keys.dob == modelDob - guard case .success(let queriedModel) = queryModelSynchronous(modelType: ModelCompositePk.self, - predicate: predicate) else { + guard case .success(let queriedModel) = queryModelSynchronous( + modelType: ModelCompositePk.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -118,11 +128,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let completed = expectation(description: "operation completed") let identifier = ModelCompositePk.IdentifierProtocol.identifier(id: modelId, dob: modelDob) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: ModelCompositePk.self, - modelSchema: ModelCompositePk.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: ModelCompositePk.self, + modelSchema: ModelCompositePk.schema, + withIdentifier: identifier + ) { result in switch result { case .success(let model): XCTAssertNotNil(model) @@ -133,8 +145,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed], timeout: 1) - guard case .success(let queriedModel) = queryModelSynchronous(modelType: ModelCompositePk.self, - predicate: predicate) else { + guard case .success(let queriedModel) = queryModelSynchronous( + modelType: ModelCompositePk.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -150,8 +164,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -159,12 +175,14 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { XCTAssertEqual(queriedRestaurants.first!.restaurantName, restaurantName) let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier, - condition: Restaurant.keys.restaurantName.eq(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier, + condition: Restaurant.keys.restaurantName.eq(restaurantName) + ) { result in switch result { case .success(let restaurant): XCTAssertNotNil(restaurant) @@ -175,8 +193,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -192,8 +212,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -201,12 +223,14 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { XCTAssertEqual(queriedRestaurants.first!.restaurantName, restaurantName) let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier, - condition: Restaurant.keys.restaurantName.ne(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier, + condition: Restaurant.keys.restaurantName.ne(restaurantName) + ) { result in switch result { case .success: XCTFail("Should have been invalid condition error") @@ -220,8 +244,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -238,19 +264,23 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } XCTAssertEqual(queriedRestaurants.count, 1) XCTAssertEqual(queriedRestaurants.first!.restaurantName, restaurantName) let completed = expectation(description: "operation completed") - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - filter: Restaurant.keys.restaurantName.eq(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + filter: Restaurant.keys.restaurantName.eq(restaurantName) + ) { result in switch result { case .success(let restaurants): XCTAssertEqual(restaurants.count, 1) @@ -262,8 +292,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -279,19 +311,23 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } XCTAssertEqual(queriedRestaurants.count, 1) XCTAssertEqual(queriedRestaurants.first!.restaurantName, restaurantName) let completed = expectation(description: "operation completed") - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: nil, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - filter: Restaurant.keys.restaurantName.ne(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: nil, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + filter: Restaurant.keys.restaurantName.ne(restaurantName) + ) { result in switch result { case .success(let restaurants): XCTAssertEqual(restaurants.count, 0) @@ -302,8 +338,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -320,8 +358,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { return } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id - guard case .success(let queriedRestaurants) = await queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = await queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -347,11 +387,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier + ) { result in switch result { case .success(let restaurant): XCTAssertNotNil(restaurant) @@ -363,8 +405,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { operation.start() await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess, completed], timeout: 1) - guard case .success(let queriedRestaurants) = await queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = await queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -382,8 +426,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = ModelCompositePk.keys.id == modelId && ModelCompositePk.keys.dob == modelDob - guard case .success(let queriedModels) = await queryModelSynchronous(modelType: ModelCompositePk.self, - predicate: predicate) else { + guard case .success(let queriedModels) = await queryModelSynchronous( + modelType: ModelCompositePk.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -409,11 +455,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let completed = expectation(description: "operation completed") let identifier = ModelCompositePk.IdentifierProtocol.identifier(id: modelId, dob: modelDob) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: ModelCompositePk.self, - modelSchema: ModelCompositePk.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: ModelCompositePk.self, + modelSchema: ModelCompositePk.schema, + withIdentifier: identifier + ) { result in switch result { case .success(let restaurant): XCTAssertNotNil(restaurant) @@ -424,8 +472,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess, completed], timeout: 1) - guard case .success(let queriedModels) = await queryModelSynchronous(modelType: ModelCompositePk.self, - predicate: predicate) else { + guard case .success(let queriedModels) = await queryModelSynchronous( + modelType: ModelCompositePk.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -441,8 +491,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -469,12 +521,14 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier, - condition: Restaurant.keys.restaurantName.eq(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier, + condition: Restaurant.keys.restaurantName.eq(restaurantName) + ) { result in switch result { case .success(let restaurant): XCTAssertNotNil(restaurant) @@ -485,8 +539,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed, receivedMutationEvent, expectedFailures, expectedSuccess], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -502,8 +558,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let predicate: QueryPredicate = Restaurant.keys.id == restaurant.id && Restaurant.keys.restaurantName == restaurantName - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -516,7 +574,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let expectedSuccess = expectation(description: "Simulated success on mutation event submitted to sync engine") expectedSuccess.expectedFulfillmentCount = 1 - + syncEngine.setCallbackOnSubmit { submittedMutationEvent, completion in receivedMutationEvent.fulfill() if submittedMutationEvent.modelId == restaurant.id { @@ -529,11 +587,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let completed = expectation(description: "operation completed") - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - filter: Restaurant.keys.restaurantName.eq(restaurantName)) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + filter: Restaurant.keys.restaurantName.eq(restaurantName) + ) { result in switch result { case .success(let restaurants): XCTAssertEqual(restaurants.count, 1) @@ -545,8 +605,10 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() wait(for: [completed, receivedMutationEvent, expectedFailures, expectedSuccess], timeout: 1) - guard case .success(let queriedRestaurants) = queryModelSynchronous(modelType: Restaurant.self, - predicate: predicate) else { + guard case .success(let queriedRestaurants) = queryModelSynchronous( + modelType: Restaurant.self, + predicate: predicate + ) else { XCTFail("Failed to query") return } @@ -562,11 +624,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { return } let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier) { _ in } + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier + ) { _ in } let result = await operation.queryAndDeleteTransaction() switch result { @@ -612,11 +676,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier + ) { result in switch result { case .success: completed.fulfill() @@ -645,7 +711,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { expectedSuccess.expectedFulfillmentCount = 3 var submittedEvents = [MutationEvent]() - + syncEngine.setCallbackOnSubmit { submittedMutationEvent, completion in submittedEvents.append(submittedMutationEvent) receivedMutationEvent.fulfill() @@ -683,11 +749,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { let completed = expectation(description: "operation completed") let identifier = PostWithCompositeKey.IdentifierProtocol.identifier(id: post.id, title: post.title) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: PostWithCompositeKey.self, - modelSchema: PostWithCompositeKey.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: PostWithCompositeKey.self, + modelSchema: PostWithCompositeKey.schema, + withIdentifier: identifier + ) { result in switch result { case .success: completed.fulfill() @@ -715,7 +783,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { expectedSuccess.expectedFulfillmentCount = 2 var submittedEvents = [MutationEvent]() - + syncEngine.setCallbackOnSubmit { submittedMutationEvent, completion in submittedEvents.append(submittedMutationEvent) receivedMutationEvent.fulfill() @@ -751,11 +819,13 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } let completed = expectation(description: "operation completed") let identifier = DefaultModelIdentifier.makeDefault(id: restaurant.id) - let operation = CascadeDeleteOperation(storageAdapter: storageAdapter, - syncEngine: syncEngine, - modelType: Restaurant.self, - modelSchema: Restaurant.schema, - withIdentifier: identifier) { result in + let operation = CascadeDeleteOperation( + storageAdapter: storageAdapter, + syncEngine: syncEngine, + modelType: Restaurant.self, + modelSchema: Restaurant.schema, + withIdentifier: identifier + ) { result in switch result { case .success: XCTFail("Should have failed") @@ -784,7 +854,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { expectedSuccess.expectedFulfillmentCount = 2 var submittedEvents = [MutationEvent]() - + syncEngine.setCallbackOnSubmit { submittedMutationEvent, completion in submittedEvents.append(submittedMutationEvent) receivedMutationEvent.fulfill() diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift index 6f189b06bb..fea95315a4 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift @@ -12,6 +12,7 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSDataStorePlugin + class StorageEnginePublisherTests: StorageEngineTestsBase { override func setUp() { @@ -23,11 +24,13 @@ class StorageEnginePublisherTests: StorageEngineTestsBase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -35,18 +38,22 @@ class StorageEnginePublisherTests: StorageEngineTestsBase { } func testStorageEnginePublisherEvents() { - let modelSyncedEvent = ModelSyncedEvent(modelName: "", - isFullSync: true, - isDeltaSync: false, - added: 1, - updated: 1, - deleted: 1) - let mutationEvent = MutationEvent(id: "", - modelId: "", - modelName: "", - json: "", - mutationType: .create, - createdAt: .now()) + let modelSyncedEvent = ModelSyncedEvent( + modelName: "", + isFullSync: true, + isDeltaSync: false, + added: 1, + updated: 1, + deleted: 1 + ) + let mutationEvent = MutationEvent( + id: "", + modelId: "", + modelName: "", + json: "", + mutationType: .create, + createdAt: .now() + ) let receivedMutationEvent = expectation(description: "Received mutationEvent event") let receivedModelSyncedEvent = expectation(description: "Received ModelSynced event") let receivedSyncQueriesReadyEvent = expectation(description: "Received syncQueries event") diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift index bdd3ef26ac..0928490153 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift @@ -38,7 +38,7 @@ class StorageEngineTestsBase: XCTestCase { } return saveResult } - + func saveModelSynchronous(model: M) async -> DataStoreResult { let saveFinished = expectation(description: "Save finished") var result: DataStoreResult? @@ -62,7 +62,7 @@ class StorageEngineTestsBase: XCTestCase { } } } - + func querySingleModelSynchronous(modelType: M.Type, predicate: QueryPredicate) -> DataStoreResult { let result = queryModelSynchronous(modelType: modelType, predicate: predicate) @@ -95,7 +95,7 @@ class StorageEngineTestsBase: XCTestCase { } return queryResult } - + func queryModelSynchronous(modelType: M.Type, predicate: QueryPredicate) async -> DataStoreResult<[M]> { let queryFinished = expectation(description: "Query Finished") var result: DataStoreResult<[M]>? @@ -111,14 +111,16 @@ class StorageEngineTestsBase: XCTestCase { } return queryResult } - - func queryAsync(_ modelType: M.Type, - byIdentifier identifier: String, - eagerLoad: Bool = true) async throws -> M? { + + func queryAsync( + _ modelType: M.Type, + byIdentifier identifier: String, + eagerLoad: Bool = true + ) async throws -> M? { let predicate: QueryPredicate = field("id").eq(identifier) return try await queryAsync(modelType, predicate: predicate, eagerLoad: eagerLoad).first } - + func queryAsync(_ modelType: M.Type, predicate: QueryPredicate? = nil, eagerLoad: Bool = true) async throws -> [M] { try await withCheckedThrowingContinuation { continuation in storageEngine.query(modelType, predicate: predicate, eagerLoad: eagerLoad) { qResult in @@ -126,10 +128,12 @@ class StorageEngineTestsBase: XCTestCase { } } } - - func queryStorageAdapter(_ modelType: M.Type, - byIdentifier identifier: String, - eagerLoad: Bool = true) async throws -> M? { + + func queryStorageAdapter( + _ modelType: M.Type, + byIdentifier identifier: String, + eagerLoad: Bool = true + ) async throws -> M? { let predicate: QueryPredicate = field("id").eq(identifier) return try await withCheckedThrowingContinuation { continuation in storageAdapter.query(modelType, predicate: predicate) { result in @@ -138,17 +142,21 @@ class StorageEngineTestsBase: XCTestCase { }.first } - func deleteModelSynchronousOrFailOtherwise(modelType: M.Type, - withId id: String, - where predicate: QueryPredicate? = nil, - timeout: TimeInterval = 1) -> DataStoreResult { - let result = deleteModelSynchronous(modelType: modelType, - withId: id, - where: predicate, - timeout: timeout) + func deleteModelSynchronousOrFailOtherwise( + modelType: M.Type, + withId id: String, + where predicate: QueryPredicate? = nil, + timeout: TimeInterval = 1 + ) -> DataStoreResult { + let result = deleteModelSynchronous( + modelType: modelType, + withId: id, + where: predicate, + timeout: timeout + ) switch result { case .success(let model): - if let model = model { + if let model { return .success(model) } else { return .failure(causedBy: "") @@ -158,21 +166,25 @@ class StorageEngineTestsBase: XCTestCase { } } - func deleteModelSynchronous(modelType: M.Type, - withId id: String, - where predicate: QueryPredicate? = nil, - timeout: TimeInterval = 10) -> DataStoreResult { + func deleteModelSynchronous( + modelType: M.Type, + withId id: String, + where predicate: QueryPredicate? = nil, + timeout: TimeInterval = 10 + ) -> DataStoreResult { let deleteFinished = expectation(description: "Delete Finished") var result: DataStoreResult? - storageEngine.delete(modelType, - modelSchema: modelType.schema, - withId: id, - condition: predicate, - completion: { dResult in + storageEngine.delete( + modelType, + modelSchema: modelType.schema, + withId: id, + condition: predicate, + completion: { dResult in result = dResult deleteFinished.fulfill() - }) + } + ) wait(for: [deleteFinished], timeout: timeout) guard let deleteResult = result else { @@ -180,15 +192,19 @@ class StorageEngineTestsBase: XCTestCase { } return deleteResult } - - func deleteAsync(modelType: M.Type, - withId id: String, - where predicate: QueryPredicate? = nil) async throws -> M? { + + func deleteAsync( + modelType: M.Type, + withId id: String, + where predicate: QueryPredicate? = nil + ) async throws -> M? { try await withCheckedThrowingContinuation { continuation in - storageEngine.delete(modelType, - modelSchema: modelType.schema, - withId: id, - condition: predicate) { dResult in + storageEngine.delete( + modelType, + modelSchema: modelType.schema, + withId: id, + condition: predicate + ) { dResult in continuation.resume(with: dResult) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift index 14e44c62ac..efa786e685 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift @@ -27,11 +27,13 @@ class StorageEngineTestsDelete: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: Team.self) ModelRegistry.register(modelType: Project.self) @@ -60,8 +62,10 @@ class StorageEngineTestsDelete: StorageEngineTestsBase { func testDeleteSuccessWhenItemDoesNotExist() { let teamA = Team(name: "A-Team") let projectA = Project(name: "ProjectA", team: teamA) - let result = deleteModelSynchronous(modelType: Project.self, - withId: projectA.id) + let result = deleteModelSynchronous( + modelType: Project.self, + withId: projectA.id + ) switch result { case .success(let model): guard model == nil else { @@ -77,9 +81,11 @@ class StorageEngineTestsDelete: StorageEngineTestsBase { let teamA = Team(name: "A-Team") let projectA = Project(name: "ProjectA", team: teamA) let project = Project.keys - let result = deleteModelSynchronous(modelType: Project.self, - withId: projectA.id, - where: project.name == "ProjectA") + let result = deleteModelSynchronous( + modelType: Project.self, + withId: projectA.id, + where: project.name == "ProjectA" + ) switch result { case .success(let model): guard model == nil else { @@ -111,9 +117,11 @@ class StorageEngineTestsDelete: StorageEngineTestsBase { return } let project = Project.keys - let result = deleteModelSynchronous(modelType: Project.self, - withId: projectA.id, - where: project.name == "NotProjectA") + let result = deleteModelSynchronous( + modelType: Project.self, + withId: projectA.id, + where: project.name == "NotProjectA" + ) switch result { case .success: @@ -163,9 +171,11 @@ class StorageEngineTestsDelete: StorageEngineTestsBase { } let project = Project.keys - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: Project.self, - withId: projectA.id, - where: project.name == "ProjectA") else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: Project.self, + withId: projectA.id, + where: project.name == "ProjectA" + ) else { XCTFail("Failed to delete projectA") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift index 98234107dc..859dc66a78 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift @@ -28,11 +28,13 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: Restaurant.self) ModelRegistry.register(modelType: Menu.self) ModelRegistry.register(modelType: Dish.self) @@ -83,8 +85,10 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { } guard case .success = - querySingleModelSynchronous(modelType: Restaurant.self, - predicate: Restaurant.keys.id == dreamRestaurant.id) else { + querySingleModelSynchronous( + modelType: Restaurant.self, + predicate: Restaurant.keys.id == dreamRestaurant.id + ) else { XCTFail("Failed to query Restaurant") return } @@ -106,8 +110,10 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { receivedMutationEvent.fulfill() completion(.success(submittedMutationEvent)) } - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: Restaurant.self, - withId: dreamRestaurant.id) else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: Restaurant.self, + withId: dreamRestaurant.id + ) else { XCTFail("Failed to delete restaurant") return } @@ -169,22 +175,28 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { } // Query individually without lazy loading and verify counts. guard case .success(let savedRestaurant) = - querySingleModelSynchronous(modelType: Restaurant.self, - predicate: Restaurant.keys.id == restaurant1.id) else { + querySingleModelSynchronous( + modelType: Restaurant.self, + predicate: Restaurant.keys.id == restaurant1.id + ) else { XCTFail("Failed to query Restaurant") return } XCTAssertEqual(savedRestaurant.id, restaurant1.id) guard case .success(let menus) = - queryModelSynchronous(modelType: Menu.self, - predicate: QueryPredicateConstant.all) else { + queryModelSynchronous( + modelType: Menu.self, + predicate: QueryPredicateConstant.all + ) else { XCTFail("Failed to query menus") return } XCTAssertEqual(menus.count, numberOfMenus) guard case .success(let dishes) = - queryModelSynchronous(modelType: Dish.self, - predicate: QueryPredicateConstant.all) else { + queryModelSynchronous( + modelType: Dish.self, + predicate: QueryPredicateConstant.all + ) else { XCTFail("Failed to query dishes") return } @@ -198,9 +210,11 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { receivedMutationEvent.fulfill() completion(.success(submittedMutationEvent)) } - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: Restaurant.self, - withId: restaurant1.id, - timeout: 100) else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: Restaurant.self, + withId: restaurant1.id, + timeout: 100 + ) else { XCTFail("Failed to delete restaurant") return } @@ -240,8 +254,10 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { } } - guard case .failure(let error) = deleteModelSynchronousOrFailOtherwise(modelType: Restaurant.self, - withId: restaurant1.id) else { + guard case .failure(let error) = deleteModelSynchronousOrFailOtherwise( + modelType: Restaurant.self, + withId: restaurant1.id + ) else { XCTFail("Deleting should have failed due to our mock") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift index 2627faa3a0..4e5e6ed2e7 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift @@ -27,11 +27,13 @@ class StorageEngineTestsHasOne: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: Team.self) ModelRegistry.register(modelType: Project.self) @@ -81,7 +83,7 @@ class StorageEngineTestsHasOne: StorageEngineTestsBase { saveFinished.fulfill() } guard case .failure(let error) = result, - case . invalidCondition(let errorDescription, let recoverySuggestion, _) = error else { + case .invalidCondition(let errorDescription, let recoverySuggestion, _) = error else { XCTFail("Expected failure with .invalidCondition, got \(result)") return } @@ -127,8 +129,10 @@ class StorageEngineTestsHasOne: StorageEngineTestsBase { mutationEventOnProject.fulfill() completion(.success(submittedMutationEvent)) } - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: Project.self, - withId: projectA.id) else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: Project.self, + withId: projectA.id + ) else { XCTFail("Failed to delete projectA") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsLazyPostComment4V2Tests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsLazyPostComment4V2Tests.swift index 62f06849b6..c6425bb0fb 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsLazyPostComment4V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsLazyPostComment4V2Tests.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation import SQLite import XCTest @@ -15,28 +14,30 @@ import XCTest @testable import AWSDataStorePlugin final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, SharedTestCasesPostComment4V2 { - + override func setUp() { super.setUp() Amplify.Logging.logLevel = .verbose - + let validAPIPluginKey = "MockAPICategoryPlugin" let validAuthPluginKey = "MockAuthCategoryPlugin" do { connection = try Connection(.inMemory) storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - + syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) - + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) + ModelListDecoderRegistry.registerDecoder(DataStoreListDecoder.self) ModelProviderRegistry.registerDecoder(DataStoreModelDecoder.self) - + ModelRegistry.register(modelType: LazyParentPost4V2.self) ModelRegistry.register(modelType: LazyChildComment4V2.self) do { @@ -50,7 +51,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S return } } - + func testSaveCommentThenQueryComment() async throws { let comment = LazyChildComment4V2(content: "content") let savedComment = try await saveAsync(comment) @@ -58,13 +59,15 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S switch savedComment._post.modelProvider.getState() { case .notLoaded(let identifiers): XCTAssertNil(identifiers) - + case .loaded: XCTFail("should be loaded, with `nil` element") } - guard let queriedComment = try await queryAsync(LazyChildComment4V2.self, - byIdentifier: comment.id, - eagerLoad: true) else { + guard let queriedComment = try await queryAsync( + LazyChildComment4V2.self, + byIdentifier: comment.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved comment") return } @@ -76,15 +79,17 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("should be not loaded, with `nil` identifiers") } } - + func testSavePostThenQueryPost() async throws { let post = LazyParentPost4V2(title: "title") let savedPost = try await saveAsync(post) XCTAssertEqual(savedPost.id, post.id) - - guard let queriedPost = try await queryAsync(LazyParentPost4V2.self, - byIdentifier: post.id, - eagerLoad: true) else { + + guard let queriedPost = try await queryAsync( + LazyParentPost4V2.self, + byIdentifier: post.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved post") return } @@ -99,39 +104,45 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("missing comments") } } - + func testSaveMultipleThenQueryComments() async throws { try await saveAsync(LazyChildComment4V2(content: "content")) try await saveAsync(LazyChildComment4V2(content: "content")) - - let comments = try await queryAsync(LazyChildComment4V2.self, - eagerLoad: true) + + let comments = try await queryAsync( + LazyChildComment4V2.self, + eagerLoad: true + ) XCTAssertEqual(comments.count, 2) } - + func testSaveMultipleThenQueryPosts() async throws { try await saveAsync(LazyParentPost4V2(title: "title")) try await saveAsync(LazyParentPost4V2(title: "title")) - - let comments = try await queryAsync(LazyParentPost4V2.self, - eagerLoad: true) + + let comments = try await queryAsync( + LazyParentPost4V2.self, + eagerLoad: true + ) XCTAssertEqual(comments.count, 2) } - + func testCommentWithPost_TranslateToStorageValues() async throws { let post = LazyParentPost4V2(id: "postId", title: "title") _ = try await saveAsync(post) var comment = LazyChildComment4V2(content: "content", post: post) - + // Model.sqlValues tesitng - let sqlValues = comment.sqlValues(for: LazyChildComment4V2.schema.columns, - modelSchema: LazyChildComment4V2.schema) + let sqlValues = comment.sqlValues( + for: LazyChildComment4V2.schema.columns, + modelSchema: LazyChildComment4V2.schema + ) XCTAssertEqual(sqlValues[0] as? String, comment.id) XCTAssertEqual(sqlValues[1] as? String, comment.content) XCTAssertNil(sqlValues[2]) // createdAt XCTAssertNil(sqlValues[3]) // updatedAt XCTAssertEqual(sqlValues[4] as? String, post.id) - + // Insert let insertStatement = InsertStatement(model: comment, modelSchema: LazyChildComment4V2.schema) XCTAssertEqual(insertStatement.variables[0] as? String, comment.id) @@ -140,61 +151,75 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTAssertNil(insertStatement.variables[3]) // updatedAt XCTAssertEqual(insertStatement.variables[4] as? String, post.id) _ = try connection.prepare(insertStatement.stringValue).run(insertStatement.variables) - + // Update comment.content = "updatedContent" - let updateStatement = UpdateStatement(model: comment, - modelSchema: LazyChildComment4V2.schema, - condition: nil) + let updateStatement = UpdateStatement( + model: comment, + modelSchema: LazyChildComment4V2.schema, + condition: nil + ) _ = try connection.prepare(updateStatement.stringValue).run(updateStatement.variables) - + // Select with eagerLoad true - let selectStatement = SelectStatement(from: LazyChildComment4V2.schema, - predicate: field("id").eq(comment.id), - sort: nil, - paginationInput: nil, - eagerLoad: true) + let selectStatement = SelectStatement( + from: LazyChildComment4V2.schema, + predicate: field("id").eq(comment.id), + sort: nil, + paginationInput: nil, + eagerLoad: true + ) let rows = try connection.prepare(selectStatement.stringValue).run(selectStatement.variables) - _ = try rows.convertToModelValues(to: LazyChildComment4V2.self, - withSchema: LazyChildComment4V2.schema, - using: selectStatement) - let comments = try rows.convert(to: LazyChildComment4V2.self, - withSchema: LazyChildComment4V2.schema, - using: selectStatement) + _ = try rows.convertToModelValues( + to: LazyChildComment4V2.self, + withSchema: LazyChildComment4V2.schema, + using: selectStatement + ) + let comments = try rows.convert( + to: LazyChildComment4V2.self, + withSchema: LazyChildComment4V2.schema, + using: selectStatement + ) XCTAssertEqual(comments.count, 1) guard let comment = comments.first else { XCTFail("Should retrieve single comment") return } - + XCTAssertEqual(comment.content, "updatedContent") switch comment._post.modelProvider.getState() { case .notLoaded: XCTFail("Should have been loaded") case .loaded(let post): - guard let post = post else { + guard let post else { XCTFail("Loaded with no post") return } XCTAssertEqual(post.id, "postId") XCTAssertEqual(post.title, "title") } - + // Select with eagerLoad false - let selectStatement2 = SelectStatement(from: LazyChildComment4V2.schema, - predicate: field("id").eq(comment.id), - sort: nil, - paginationInput: nil, - eagerLoad: false) + let selectStatement2 = SelectStatement( + from: LazyChildComment4V2.schema, + predicate: field("id").eq(comment.id), + sort: nil, + paginationInput: nil, + eagerLoad: false + ) let rows2 = try connection.prepare(selectStatement2.stringValue).run(selectStatement2.variables) - _ = try rows2.convertToModelValues(to: LazyChildComment4V2.self, - withSchema: LazyChildComment4V2.schema, - using: selectStatement2, - eagerLoad: false) - let comments2 = try rows2.convert(to: LazyChildComment4V2.self, - withSchema: LazyChildComment4V2.schema, - using: selectStatement2, - eagerLoad: false) + _ = try rows2.convertToModelValues( + to: LazyChildComment4V2.self, + withSchema: LazyChildComment4V2.schema, + using: selectStatement2, + eagerLoad: false + ) + let comments2 = try rows2.convert( + to: LazyChildComment4V2.self, + withSchema: LazyChildComment4V2.schema, + using: selectStatement2, + eagerLoad: false + ) XCTAssertEqual(comments.count, 1) guard let comment2 = comments2.first else { XCTFail("Should retrieve single comment") @@ -204,7 +229,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTAssertEqual(comment2.content, "updatedContent") switch comment2._post.modelProvider.getState() { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { XCTFail("Missing identifiers") return } @@ -213,13 +238,13 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("Should be not loaded") } } - + func testSaveCommentWithPostThenQueryCommentAndAccessPost() async throws { let post = LazyParentPost4V2(title: "title") try await saveAsync(post) let comment = LazyChildComment4V2(content: "content", post: post) let savedComment = try await saveAsync(comment) - + // The post should be eager loaded by default on a save switch savedComment._post.modelProvider.getState() { case .notLoaded: @@ -231,11 +256,13 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S } XCTAssertEqual(loadedPost.id, post.id) } - + // The query with eagerLoad should load the post - guard let queriedCommentEagerLoadedPost = try await queryAsync(LazyChildComment4V2.self, - byIdentifier: comment.id, - eagerLoad: true) else { + guard let queriedCommentEagerLoadedPost = try await queryAsync( + LazyChildComment4V2.self, + byIdentifier: comment.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved comment") return } @@ -249,11 +276,13 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S } XCTAssertEqual(loadedPost.id, post.id) } - + // The query with eagerLoad false should create a not loaded post for lazy loading - guard let queriedCommentLazyLoadedPost = try await queryAsync(LazyChildComment4V2.self, - byIdentifier: comment.id, - eagerLoad: false) else { + guard let queriedCommentLazyLoadedPost = try await queryAsync( + LazyChildComment4V2.self, + byIdentifier: comment.id, + eagerLoad: false + ) else { XCTFail("Failed to query saved comment") return } @@ -266,7 +295,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S switch queriedCommentLazyLoadedPost._post.modelProvider.getState() { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { XCTFail("Missing identifiers") return } @@ -275,16 +304,18 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("lazy loaded post should be not loaded") } } - + func testSaveCommentWithPostThenQueryPostAndAccessComments() async throws { let post = LazyParentPost4V2(title: "title") try await saveAsync(post) let comment = LazyChildComment4V2(content: "content", post: post) try await saveAsync(comment) - - guard let queriedPost = try await queryAsync(LazyParentPost4V2.self, - byIdentifier: post.id, - eagerLoad: true) else { + + guard let queriedPost = try await queryAsync( + LazyParentPost4V2.self, + byIdentifier: post.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved post") return } @@ -293,7 +324,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("Failed to get comments from queried post") return } - + switch comments.listProvider.getState() { case .notLoaded(let associatedIdentifiers, let associatedFields): XCTAssertEqual(associatedIdentifiers, [post.id]) @@ -302,7 +333,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("Should not be loaded") } } - + func testSaveMultipleCommentWithPostThenQueryCommentsAndAccessPost() async throws { let post1 = LazyParentPost4V2(id: "postId1", title: "title1") try await saveAsync(post1) @@ -315,8 +346,10 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S try await saveAsync(comment2) // Query with eagerLoad true - var comments = try await queryAsync(LazyChildComment4V2.self, - eagerLoad: true) + var comments = try await queryAsync( + LazyChildComment4V2.self, + eagerLoad: true + ) XCTAssertEqual(comments.count, 2) guard let comment1 = comments.first(where: { $0.id == "id1" }) else { @@ -341,10 +374,12 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTAssertEqual(post!.id, "postId2") XCTAssertEqual(post!.title, "title2") } - + // Query with eagerLoad false - comments = try await queryAsync(LazyChildComment4V2.self, - eagerLoad: false) + comments = try await queryAsync( + LazyChildComment4V2.self, + eagerLoad: false + ) XCTAssertEqual(comments.count, 2) guard let comment1 = comments.first(where: { $0.id == "id1" }) else { @@ -357,7 +392,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S } switch comment1._post.modelProvider.getState() { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { XCTFail("Missing identifiers") return } @@ -367,7 +402,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S } switch comment2._post.modelProvider.getState() { case .notLoaded(let identifiers): - guard let identifiers = identifiers else { + guard let identifiers else { XCTFail("Missing identifiers") return } @@ -376,7 +411,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("Should be not loaded") } } - + func testSaveMultipleCommentWithPostThenQueryPostAndAccessComments() async throws { let post1 = LazyParentPost4V2(id: "postId1", title: "title1") try await saveAsync(post1) @@ -386,7 +421,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S try await saveAsync(post2) let comment2 = LazyChildComment4V2(id: "id2", content: "content", post: post2) try await saveAsync(comment2) - + var posts = try await queryAsync(LazyParentPost4V2.self) XCTAssertEqual(posts.count, 2) guard let postId1 = posts.first(where: { $0.id == "postId1" }) else { @@ -401,7 +436,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S XCTFail("Failed to get comments from post1") return } - + switch comments1.listProvider.getState() { case .notLoaded(let associatedIdentifiers, let associatedFields): XCTAssertEqual(associatedIdentifiers, [post1.id]) @@ -409,7 +444,7 @@ final class StorageEngineTestsLazyPostComment4V2Tests: StorageEngineTestsBase, S case .loaded: XCTFail("Should not be loaded") } - + guard let comments2 = postId2.comments else { XCTFail("Failed to get comments from post2") return diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift index 4280e73a26..1d6604be01 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift @@ -27,11 +27,13 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: M2MPost.self) ModelRegistry.register(modelType: M2MPostEditor.self) ModelRegistry.register(modelType: M2MUser.self) @@ -73,20 +75,26 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { } guard case .success = - querySingleModelSynchronous(modelType: M2MPost.self, - predicate: M2MPost.keys.id == post1.id) else { + querySingleModelSynchronous( + modelType: M2MPost.self, + predicate: M2MPost.keys.id == post1.id + ) else { XCTFail("Failed to query M2MPost") return } guard case .success = - querySingleModelSynchronous(modelType: M2MPostEditor.self, - predicate: M2MPostEditor.keys.id == postEditors1.id) else { + querySingleModelSynchronous( + modelType: M2MPostEditor.self, + predicate: M2MPostEditor.keys.id == postEditors1.id + ) else { XCTFail("Failed to query M2MPostEditor") return } guard case .success = - querySingleModelSynchronous(modelType: M2MUser.self, - predicate: M2MUser.keys.id == user1.id) else { + querySingleModelSynchronous( + modelType: M2MUser.self, + predicate: M2MUser.keys.id == user1.id + ) else { XCTFail("Failed to query M2MUser") return } @@ -98,8 +106,10 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { mutationEvents.fulfill() completion(.success(submittedMutationEvent)) } - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: M2MPost.self, - withId: post1.id) else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: M2MPost.self, + withId: post1.id + ) else { XCTFail("Failed to delete post1") return } @@ -130,20 +140,26 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { } guard case .success = - querySingleModelSynchronous(modelType: M2MPost.self, - predicate: M2MPost.keys.id == post1.id) else { + querySingleModelSynchronous( + modelType: M2MPost.self, + predicate: M2MPost.keys.id == post1.id + ) else { XCTFail("Failed to query M2MPost") return } guard case .success = - querySingleModelSynchronous(modelType: M2MPostEditor.self, - predicate: M2MPostEditor.keys.id == postEditors1.id) else { + querySingleModelSynchronous( + modelType: M2MPostEditor.self, + predicate: M2MPostEditor.keys.id == postEditors1.id + ) else { XCTFail("Failed to query M2MPostEditor") return } guard case .success = - querySingleModelSynchronous(modelType: M2MUser.self, - predicate: M2MUser.keys.id == user1.id) else { + querySingleModelSynchronous( + modelType: M2MUser.self, + predicate: M2MUser.keys.id == user1.id + ) else { XCTFail("Failed to query M2MUser") return } @@ -155,8 +171,10 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { mutationEvents.fulfill() completion(.success(submittedMutationEvent)) } - guard case .success = deleteModelSynchronousOrFailOtherwise(modelType: M2MUser.self, - withId: user1.id) else { + guard case .success = deleteModelSynchronousOrFailOtherwise( + modelType: M2MUser.self, + withId: user1.id + ) else { XCTFail("Failed to delete post1") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsOptionalAssociation.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsOptionalAssociation.swift index ef740ed914..9b2dc3f91f 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsOptionalAssociation.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsOptionalAssociation.swift @@ -27,11 +27,13 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: Blog8.self) ModelRegistry.register(modelType: Post8.self) ModelRegistry.register(modelType: Comment8.self) @@ -56,8 +58,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { } guard case let .success(queriedComment) = - querySingleModelSynchronous(modelType: Comment8.self, - predicate: Comment8.keys.id == comment.id) else { + querySingleModelSynchronous( + modelType: Comment8.self, + predicate: Comment8.keys.id == comment.id + ) else { XCTFail("Failed to query post") return } @@ -73,8 +77,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { } guard case let .success(queriedPost) = - querySingleModelSynchronous(modelType: Post8.self, - predicate: Post8.keys.id == post.id) else { + querySingleModelSynchronous( + modelType: Post8.self, + predicate: Post8.keys.id == post.id + ) else { XCTFail("Failed to query post") return } @@ -92,8 +98,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { } guard case let .success(queriedBlog) = - querySingleModelSynchronous(modelType: Blog8.self, - predicate: Blog8.keys.id == blog.id) else { + querySingleModelSynchronous( + modelType: Blog8.self, + predicate: Blog8.keys.id == blog.id + ) else { XCTFail("Failed to query blog") return } @@ -119,8 +127,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { return } guard case let .success(queriedComment) = - querySingleModelSynchronous(modelType: Comment8.self, - predicate: Comment8.keys.id == comment.id) else { + querySingleModelSynchronous( + modelType: Comment8.self, + predicate: Comment8.keys.id == comment.id + ) else { XCTFail("Failed to query post") return } @@ -148,8 +158,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { } guard case let .success(updatedPost) = - querySingleModelSynchronous(modelType: Post8.self, - predicate: Post8.keys.id == post.id) else { + querySingleModelSynchronous( + modelType: Post8.self, + predicate: Post8.keys.id == post.id + ) else { XCTFail("Failed to query post") return } @@ -180,8 +192,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { } guard case let .success(queriedComment) = - querySingleModelSynchronous(modelType: Comment8.self, - predicate: Comment8.keys.id == comment.id) else { + querySingleModelSynchronous( + modelType: Comment8.self, + predicate: Comment8.keys.id == comment.id + ) else { XCTFail("Failed to query comment") return } @@ -203,8 +217,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { return } guard case let .success(queriedComment) = - querySingleModelSynchronous(modelType: Comment8.self, - predicate: Comment8.keys.id == comment.id) else { + querySingleModelSynchronous( + modelType: Comment8.self, + predicate: Comment8.keys.id == comment.id + ) else { XCTFail("Failed to query comment") return } @@ -217,8 +233,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { return } guard case let .success(queriedComment) = - querySingleModelSynchronous(modelType: Comment8.self, - predicate: Comment8.keys.id == comment.id) else { + querySingleModelSynchronous( + modelType: Comment8.self, + predicate: Comment8.keys.id == comment.id + ) else { XCTFail("Failed to query comment") return } @@ -229,8 +247,10 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { return } guard case let .success(queriedPost) = - querySingleModelSynchronous(modelType: Post8.self, - predicate: Post8.keys.id == post.id) else { + querySingleModelSynchronous( + modelType: Post8.self, + predicate: Post8.keys.id == post.id + ) else { XCTFail("Failed to query post") return } @@ -243,18 +263,22 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { XCTFail("Failed to save post") return } - let statement = SelectStatement(from: Post8.schema, - predicate: nil, - sort: nil, - paginationInput: nil) + let statement = SelectStatement( + from: Post8.schema, + predicate: nil, + sort: nil, + paginationInput: nil + ) let rows = try connection.prepare(statement.stringValue).run(statement.variables) // Eager loading selects all fields and associated fields. The number of columns is the number of fields of // Post8 plus it's associated field Blog8. This excludes the association itself, ie. post.blog is excluded // and blog.posts is excluded. So there are 6 Post8 fields and 6 Blog8 fields. XCTAssertEqual(rows.columnCount, 12) - let results: [Post8] = try rows.convert(to: Post8.self, - withSchema: Post8.schema, - using: statement) + let results: [Post8] = try rows.convert( + to: Post8.self, + withSchema: Post8.schema, + using: statement + ) XCTAssertNotNil(results) // The result is the single post which was saved and queried @@ -279,14 +303,18 @@ class StorageEngineTestsOptionalAssociation: StorageEngineTestsBase { return } - let statement = SelectStatement(from: Post8.schema, - predicate: nil, - sort: nil, - paginationInput: nil) + let statement = SelectStatement( + from: Post8.schema, + predicate: nil, + sort: nil, + paginationInput: nil + ) let rows = try connection.prepare(statement.stringValue).run(statement.variables) - let results: [Post8] = try rows.convert(to: Post8.self, - withSchema: Post8.schema, - using: statement) + let results: [Post8] = try rows.convert( + to: Post8.self, + withSchema: Post8.schema, + using: statement + ) XCTAssertNotNil(results) XCTAssertEqual(results.count, 1) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsPostComment4V2Tests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsPostComment4V2Tests.swift index 25db881a49..00459a4cbd 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsPostComment4V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsPostComment4V2Tests.swift @@ -27,15 +27,17 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) - + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) + ModelListDecoderRegistry.registerDecoder(DataStoreListDecoder.self) ModelProviderRegistry.registerDecoder(DataStoreModelDecoder.self) - + ModelRegistry.register(modelType: ParentPost4V2.self) ModelRegistry.register(modelType: ChildComment4V2.self) do { @@ -55,8 +57,9 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share let expectedSuccess = expectation(description: "Simulated success on mutation event submitted to sync engine") let post = ParentPost4V2( id: "postId1", - title: "title1") - + title: "title1" + ) + syncEngine.setCallbackOnSubmit { submittedMutationEvent, completion in receivedMutationEvent.fulfill() if submittedMutationEvent.modelId == post.id { @@ -69,9 +72,9 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share } try await saveAsync(post) await fulfillment(of: [receivedMutationEvent, expectedSuccess], timeout: 1) - + } - + /// A save should fail if the corresponding MutationEvent could not be submitted to the syncEngine. func testSavePostFailDueToSyncEngineMissing() async throws { storageEngine.syncEngine = nil @@ -79,7 +82,8 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share try await saveAsync( ParentPost4V2( id: "postId1", - title: "title1")) + title: "title1" + )) XCTFail("Expected to fail when sync engine is `nil`") } catch { guard let dataStoreError = error as? DataStoreError else { @@ -88,112 +92,129 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share } XCTAssertEqual( dataStoreError.errorDescription, - "No SyncEngine available to sync mutation event, rollback save.") + "No SyncEngine available to sync mutation event, rollback save." + ) } } - + func testSaveCommentThenQueryComment() async throws { let comment = ChildComment4V2(content: "content") let savedComment = try await saveAsync(comment) XCTAssertEqual(savedComment.id, comment.id) - - guard let queriedComment = try await queryAsync(ChildComment4V2.self, - byIdentifier: comment.id, - eagerLoad: true) else { + + guard let queriedComment = try await queryAsync( + ChildComment4V2.self, + byIdentifier: comment.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved comment") return } XCTAssertEqual(queriedComment.id, comment.id) } - + func testSavePostThenQueryPost() async throws { let post = ParentPost4V2(title: "title") let savedPost = try await saveAsync(post) XCTAssertEqual(savedPost.id, post.id) - - guard let queriedPost = try await queryAsync(ParentPost4V2.self, - byIdentifier: post.id, - eagerLoad: true) else { + + guard let queriedPost = try await queryAsync( + ParentPost4V2.self, + byIdentifier: post.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved post") return } XCTAssertEqual(queriedPost.id, post.id) } - + func testSaveMultipleThenQueryComments() async throws { try await saveAsync(ChildComment4V2(content: "content")) try await saveAsync(ChildComment4V2(content: "content")) - + let comments = try await queryAsync(ChildComment4V2.self, eagerLoad: true) XCTAssertEqual(comments.count, 2) } - + func testSaveMultipleThenQueryPosts() async throws { try await saveAsync(ParentPost4V2(title: "title")) try await saveAsync(ParentPost4V2(title: "title")) - + let comments = try await queryAsync(ParentPost4V2.self, eagerLoad: true) XCTAssertEqual(comments.count, 2) } - + // TODO: clean up this test func testCommentWithPost_TranslateToStorageValues() async throws { let post = ParentPost4V2(id: "postId", title: "title") _ = try await saveAsync(post) var comment = ChildComment4V2(content: "content", post: post) - + // Model.sqlValues testing - let sqlValues = comment.sqlValues(for: ChildComment4V2.schema.columns, - modelSchema: ChildComment4V2.schema) + let sqlValues = comment.sqlValues( + for: ChildComment4V2.schema.columns, + modelSchema: ChildComment4V2.schema + ) XCTAssertEqual(sqlValues[0] as? String, comment.id) XCTAssertEqual(sqlValues[1] as? String, comment.content) XCTAssertNil(sqlValues[2]) // createdAt XCTAssertNil(sqlValues[3]) // updatedAt XCTAssertEqual(sqlValues[4] as? String, post.id) - + // InsertStatement testing - let insertStatement = InsertStatement(model: comment, - modelSchema: ChildComment4V2.schema) + let insertStatement = InsertStatement( + model: comment, + modelSchema: ChildComment4V2.schema + ) XCTAssertEqual(insertStatement.variables[0] as? String, comment.id) XCTAssertEqual(insertStatement.variables[1] as? String, comment.content) XCTAssertNil(insertStatement.variables[2]) // createdAt XCTAssertNil(insertStatement.variables[3]) // updatedAt XCTAssertEqual(insertStatement.variables[4] as? String, post.id) _ = try connection.prepare(insertStatement.stringValue).run(insertStatement.variables) - + // UpdateStatement testing comment.content = "updatedContent" - let updateStatement = UpdateStatement(model: comment, - modelSchema: ChildComment4V2.schema, - condition: nil) + let updateStatement = UpdateStatement( + model: comment, + modelSchema: ChildComment4V2.schema, + condition: nil + ) _ = try connection.prepare(updateStatement.stringValue).run(updateStatement.variables) - - + + // Select - let selectStatement = SelectStatement(from: ChildComment4V2.schema, - predicate: field("id").eq(comment.id), - sort: nil, - paginationInput: nil, - eagerLoad: true) + let selectStatement = SelectStatement( + from: ChildComment4V2.schema, + predicate: field("id").eq(comment.id), + sort: nil, + paginationInput: nil, + eagerLoad: true + ) let rows = try connection.prepare(selectStatement.stringValue).run(selectStatement.variables) print(rows) - let result: [ModelValues] = try rows.convertToModelValues(to: ChildComment4V2.self, - withSchema: ChildComment4V2.schema, - using: selectStatement) + let result: [ModelValues] = try rows.convertToModelValues( + to: ChildComment4V2.self, + withSchema: ChildComment4V2.schema, + using: selectStatement + ) print(result) XCTAssertEqual(result.count, 1) // asert content is "updatedContent" } - + func testSaveCommentWithPostThenQueryCommentAndAccessPost() async throws { let post = ParentPost4V2(title: "title") _ = try await saveAsync(post) let comment = ChildComment4V2(content: "content", post: post) _ = try await saveAsync(comment) - - guard let queriedComment = try await queryAsync(ChildComment4V2.self, - byIdentifier: comment.id, - eagerLoad: true) else { + + guard let queriedComment = try await queryAsync( + ChildComment4V2.self, + byIdentifier: comment.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved comment") return } @@ -204,16 +225,18 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share } XCTAssertEqual(eagerLoadedPost.id, post.id) } - + func testSaveCommentWithPostThenQueryPostAndAccessComments() async throws { let post = ParentPost4V2(title: "title") _ = try await saveAsync(post) let comment = ChildComment4V2(content: "content", post: post) _ = try await saveAsync(comment) - - guard let queriedPost = try await queryAsync(ParentPost4V2.self, - byIdentifier: post.id, - eagerLoad: true) else { + + guard let queriedPost = try await queryAsync( + ParentPost4V2.self, + byIdentifier: post.id, + eagerLoad: true + ) else { XCTFail("Failed to query saved post") return } @@ -232,7 +255,7 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share XCTFail("Should not be loaded") } } - + func testSaveMultipleCommentWithPostThenQueryCommentsAndAccessPost() async throws { let post1 = try await saveAsync(ParentPost4V2(id: "postId1", title: "title1")) _ = try await saveAsync(ChildComment4V2(id: "id1", content: "content", post: post1)) @@ -261,7 +284,7 @@ final class StorageEngineTestsPostComment4V2Tests: StorageEngineTestsBase, Share XCTAssertEqual(post2.id, "postId2") XCTAssertEqual(post2.title, "title2") } - + func testSaveMultipleCommentWithPostThenQueryPostAndAccessComments() async throws { let post1 = try await saveAsync(ParentPost4V2(id: "postId1", title: "title1")) _ = try await saveAsync(ChildComment4V2(id: "id1", content: "content", post: post1)) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift index c13a16895d..c11689fe66 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift @@ -33,11 +33,13 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) syncEngine = MockRemoteSyncEngine() - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) ModelRegistry.register(modelType: CustomerSecondaryIndexV2.self) ModelRegistry.register(modelType: CustomerMultipleSecondaryIndexV2.self) @@ -74,7 +76,7 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { // 5000 - 0.0032134409993886948 - 0.00478174310119357 // 10000 - 0.0033998960039345548 - 0.006051322101324331 func testQueryPerformanceForModelWithSingleIndex() { - var averageTimeForQuery: Double = 0.0 + var averageTimeForQuery = 0.0 var iterations = 0 measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: false) { iterations += 1 @@ -85,7 +87,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { phoneNumber: randomNumericString(length: 10), accountRepresentativeID: randomCapitalCharacterString(length: 10), createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: customer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(customer)") @@ -102,7 +105,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { phoneNumber: phoneNumber, accountRepresentativeID: accountRepresentativeID, createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: uniqueCustomer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(uniqueCustomer)") @@ -113,9 +117,11 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { let startTimeQuery1 = CFAbsoluteTimeGetCurrent() startMeasuring() - guard case .success = queryModelSynchronous(modelType: CustomerSecondaryIndexV2.self, - predicate: predicate, - storageEngine: storageEngine) else { + guard case .success = queryModelSynchronous( + modelType: CustomerSecondaryIndexV2.self, + predicate: predicate, + storageEngine: storageEngine + ) else { XCTFail("Failed to query customer") return } @@ -149,7 +155,7 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { // 5000 - 0.03966123380087083 - 0.04700456840073457 // 10000 - 0.08497165249864339 - 0.09597435819596285 func testQueryPerformanceForModelWithMultipleIndexes1() { - var averageTimeForQuery: Double = 0.0 + var averageTimeForQuery = 0.0 var iterations = 0 measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: false) { iterations += 1 @@ -161,7 +167,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { age: Int.random(in: 1 ..< 100), accountRepresentativeID: randomCapitalCharacterString(length: 10), createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: customer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(customer)") @@ -179,7 +186,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { age: 30, accountRepresentativeID: accountRepresentativeID, createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: uniqueCustomer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(uniqueCustomer)") @@ -191,9 +199,11 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { let startTimeQuery1 = CFAbsoluteTimeGetCurrent() startMeasuring() - guard case .success = queryModelSynchronous(modelType: CustomerMultipleSecondaryIndexV2.self, - predicate: predicate, - storageEngine: storageEngine) else { + guard case .success = queryModelSynchronous( + modelType: CustomerMultipleSecondaryIndexV2.self, + predicate: predicate, + storageEngine: storageEngine + ) else { XCTFail("Failed to query customer") return } @@ -227,7 +237,7 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { // 5000 - 0.011302956998406444 - 0.013200746997934766 // 10000 - 0.02146193390071858 - 0.025970560003770515 func testQueryPerformanceForModelWithMultipleIndexes2() { - var averageTimeForQuery: Double = 0.0 + var averageTimeForQuery = 0.0 var iterations = 0 measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: false) { iterations += 1 @@ -239,7 +249,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { age: Int.random(in: 1 ..< 100), accountRepresentativeID: randomCapitalCharacterString(length: 10), createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: customer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(customer)") @@ -258,7 +269,8 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { age: age, accountRepresentativeID: accountRepresentativeID, createdAt: Temporal.DateTime.now(), - updatedAt: Temporal.DateTime.now()) + updatedAt: Temporal.DateTime.now() + ) guard case .success = saveModelSynchronous(model: uniqueCustomer, storageEngine: storageEngine) else { XCTFail("Failed to save customer \(uniqueCustomer)") @@ -272,9 +284,11 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { let startTimeQuery1 = CFAbsoluteTimeGetCurrent() startMeasuring() guard case .success = - queryModelSynchronous(modelType: CustomerMultipleSecondaryIndexV2.self, - predicate: predicate, - storageEngine: storageEngine) else { + queryModelSynchronous( + modelType: CustomerMultipleSecondaryIndexV2.self, + predicate: predicate, + storageEngine: storageEngine + ) else { XCTFail("Failed to query customer") return } @@ -329,9 +343,11 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { return saveResult } - func queryModelSynchronous(modelType: M.Type, - predicate: QueryPredicate, - storageEngine: StorageEngine) -> DataStoreResult<[M]> { + func queryModelSynchronous( + modelType: M.Type, + predicate: QueryPredicate, + storageEngine: StorageEngine + ) -> DataStoreResult<[M]> { let queryFinished = expectation(description: "Query Finished") var result: DataStoreResult<[M]>? diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift index 75ede3ddd9..3d2dce808d 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class ObserveQueryTaskRunnerTests: XCTestCase { var storageEngine: MockStorageEngineBehavior! @@ -24,7 +24,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { storageEngine = MockStorageEngineBehavior() dataStorePublisher = DataStorePublisher() } - + /// An item changed observed will be returned in a single snapshot /// /// - Given: The operation has started and the first query has completed. @@ -45,7 +45,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -64,14 +65,14 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) let post = try createPost(id: "1") dataStorePublisher.send(input: post) await fulfillment(of: [secondSnapshot], timeout: 10) } - + /// ObserveQuery will send a single snapshot when the sync state toggles /// from false to true. The operation internally listens to `.modelSynced` event from /// the Hub. @@ -98,7 +99,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: dispatchedModelSyncedEvent, - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -122,23 +124,32 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 5) - + dispatchedModelSyncedEvent.set(true) - let modelSyncedEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.modelSynced, - data: ModelSyncedEvent(modelName: Post.modelName, isFullSync: true, - isDeltaSync: false, added: 0, updated: 0, - deleted: 0)) + let modelSyncedEventPayload = HubPayload( + eventName: HubPayload.EventName.DataStore.modelSynced, + data: ModelSyncedEvent( + modelName: Post.modelName, + isFullSync: true, + isDeltaSync: false, + added: 0, + updated: 0, + deleted: 0 + ) + ) Amplify.Hub.dispatch(to: .dataStore, payload: modelSyncedEventPayload) await fulfillment(of: [secondSnapshot], timeout: 10) - - let modelSyncedEventNotMatch = HubPayload(eventName: HubPayload.EventName.DataStore.modelSynced, - data: ModelSyncedEvent.Builder().modelName) + + let modelSyncedEventNotMatch = HubPayload( + eventName: HubPayload.EventName.DataStore.modelSynced, + data: ModelSyncedEvent.Builder().modelName + ) Amplify.Hub.dispatch(to: .dataStore, payload: modelSyncedEventNotMatch) await fulfillment(of: [thirdSnapshot], timeout: 10) } - + /// ObserveQuery will send the first snapshot with 2 items when storage engine /// is mocked to return 2 items. /// @@ -159,10 +170,13 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) - let post = Post(title: "model1", - content: "content1", - createdAt: .now()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) + let post = Post( + title: "model1", + content: "content1", + createdAt: .now() + ) storageEngine.responders[.query] = QueryResponder(callback: { _ in return .success([post, Post(title: "model1", content: "content1", createdAt: .now())]) }) @@ -177,14 +191,14 @@ class ObserveQueryTaskRunnerTests: XCTestCase { firstSnapshot.fulfill() } } - + } catch { XCTFail("Failed with error \(error)") } } await fulfillment(of: [firstSnapshot], timeout: 10) } - + /// Multiple item changed observed will be returned in a single snapshot /// /// - Given: The operation has started and the first query has completed. @@ -206,7 +220,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -225,7 +240,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) let post1 = try createPost(id: "1") @@ -236,7 +251,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher.send(input: post3) await fulfillment(of: [secondSnapshot], timeout: 10) } - + /// Multiple published objects (more than the `.collect` count of 1000) in a relatively short time window /// will cause the operation in test to exceed the limit of 1000 in its collection of items before sending a snapshot. /// The first snapshot will have 1000 items, and subsequent snapshots will follow as the remaining objects are published and processed. @@ -262,7 +277,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -277,7 +293,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { thirdSnapshot.fulfill() } } - + XCTAssertTrue(querySnapshots.count >= 3) XCTAssertTrue(querySnapshots[0].items.count <= querySnapshots[1].items.count) XCTAssertTrue(querySnapshots[1].items.count <= querySnapshots[2].items.count) @@ -287,7 +303,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) for postId in 1 ... 1_100 { @@ -299,7 +315,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { snapshots.cancel() await fulfillment(of: [validateSnapshotsComplete], timeout: 1.0) } - + /// Cancelling the subscription will no longer receive snapshots /// /// - Given: subscriber to the operation @@ -322,7 +338,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -340,14 +357,14 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) snapshots.cancel() let post1 = try createPost(id: "1") dataStorePublisher.send(input: post1) await fulfillment(of: [secondSnapshot], timeout: 1) } - + /// Cancelling the underlying operation will emit a completion to the subscribers /// /// - Given: subscriber to the operation @@ -371,7 +388,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -397,7 +415,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { await fulfillment(of: [secondSnapshot, completedEvent], timeout: 1) } - + /// ObserveQuery's state should be able to be reset and initial query able to be started again. func testObserveQueryResetStateThenStartObserveQuery() async { let firstSnapshot = expectation(description: "first query snapshot") @@ -411,7 +429,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -428,13 +447,13 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) dataStoreStateSubject.send(.stop) dataStoreStateSubject.send(.start(storageEngine: storageEngine)) await fulfillment(of: [secondSnapshot], timeout: 1) } - + /// Multiple calls to start the observeQuery should not start again /// /// - Given: ObserverQuery operation is created, and then reset @@ -457,7 +476,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { var querySnapshots = [DataStoreQuerySnapshot]() @@ -476,7 +496,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTFail("Failed with error \(error)") } } - + await fulfillment(of: [firstSnapshot], timeout: 1) dataStoreStateSubject.send(.stop) dataStoreStateSubject.send(.start(storageEngine: storageEngine)) @@ -484,7 +504,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { await fulfillment(of: [secondSnapshot, thirdSnapshot], timeout: 1) XCTAssertTrue(taskRunner.observeQueryStarted) } - + /// 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 { @@ -499,10 +519,13 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: false), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) - let post = Post(title: "model1", - content: "content1", - createdAt: .now()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) + let post = Post( + title: "model1", + content: "content1", + createdAt: .now() + ) storageEngine.responders[.query] = QueryResponder(callback: { _ in return .success([post, Post(title: "model1", content: "content1", createdAt: .now())]) }) @@ -517,7 +540,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { } } await withTaskGroup(of: Void.self) { group in - for _ in 0..<3000 { + for _ in 0 ..< 3_000 { group.addTask { let index = Int.random(in: 1 ... 5) if index == 1 { @@ -540,7 +563,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { } await fulfillment(of: [completeReceived], timeout: 10) } - + /// When a predicate like `title.beginsWith("title")` is given, the models that matched the predicate /// should be added to the snapshots, like `post` and `post2`. When `post2.title` is updated to no longer /// match the predicate, it should be removed from the snapshot. @@ -558,7 +581,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher: dataStorePublisher, dataStoreConfiguration: .testDefault(), dispatchedModelSyncedEvent: AtomicValue(initialValue: true), - dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher()) + dataStoreStatePublisher: dataStoreStateSubject.eraseToAnyPublisher() + ) let snapshots = taskRunner.sequence Task { @@ -604,16 +628,20 @@ class ObserveQueryTaskRunnerTests: XCTestCase { dataStorePublisher.send(input: updatedPost2) await fulfillment(of: [secondSnapshot, thirdSnapshot, fourthSnapshot], timeout: 10) } - - + + // MARK: - Helpers func createPost(id: String = UUID().uuidString, title: String? = nil) throws -> MutationEvent { - try MutationEvent(model: Post(id: id, - title: title ?? "model1", - content: "content1", - createdAt: .now()), - modelSchema: Post.schema, - mutationType: MutationEvent.MutationType.create) + try MutationEvent( + model: Post( + id: id, + title: title ?? "model1", + content: "content1", + createdAt: .now() + ), + modelSchema: Post.schema, + mutationType: MutationEvent.MutationType.create + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveTaskRunnerTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveTaskRunnerTests.swift index cf6a843b52..1d701ab868 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveTaskRunnerTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveTaskRunnerTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest @testable import AWSDataStorePlugin final class ObserveTaskRunnerTests: XCTestCase { @@ -15,7 +15,7 @@ final class ObserveTaskRunnerTests: XCTestCase { let dataStorePublisher = DataStorePublisher() let runner = ObserveTaskRunner(publisher: dataStorePublisher.publisher) let sequence = runner.sequence - + let started = expectation(description: "started") let mutationEventReceived = expectation(description: "mutationEvent received") mutationEventReceived.expectedFulfillmentCount = 5 @@ -37,24 +37,28 @@ final class ObserveTaskRunnerTests: XCTestCase { } } await fulfillment(of: [started], timeout: 10.0) - var mutationEvent = MutationEvent(id: "id", - modelId: "id", - modelName: "name", - json: "json", - mutationType: .create) + var mutationEvent = MutationEvent( + id: "id", + modelId: "id", + modelName: "name", + json: "json", + mutationType: .create + ) dataStorePublisher.send(input: mutationEvent) dataStorePublisher.send(input: mutationEvent) dataStorePublisher.send(input: mutationEvent) dataStorePublisher.send(input: mutationEvent) dataStorePublisher.send(input: mutationEvent) await fulfillment(of: [mutationEventReceived], timeout: 1.0) - + task.cancel() - mutationEvent = MutationEvent(id: "id2", - modelId: "id", - modelName: "name", - json: "json", - mutationType: .create) + mutationEvent = MutationEvent( + id: "id2", + modelId: "id", + modelName: "name", + json: "json", + mutationType: .create + ) dataStorePublisher.send(input: mutationEvent) await fulfillment(of: [mutationEventReceivedAfterCancel], timeout: 1.0) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/ModelSortTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/ModelSortTests.swift index db351bf91d..33b2499beb 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/ModelSortTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/ModelSortTests.swift @@ -5,22 +5,24 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore // swiftlint:disable type_body_length class ModelSortTests: XCTestCase { func testSortModelString() throws { - var posts = [createPost(id: "1"), - createPost(id: "3"), - createPost(id: "2")] + var posts = [ + createPost(id: "1"), + createPost(id: "3"), + createPost(id: "2") + ] posts.sortModels(by: QuerySortBy.ascending(Post.keys.id).sortDescriptor, modelSchema: Post.schema) XCTAssertEqual(posts[0].id, "1") XCTAssertEqual(posts[1].id, "2") @@ -32,44 +34,61 @@ class ModelSortTests: XCTestCase { } func testSortModelOptionalString() { - var models = [QPredGen(name: "name", myString: "1"), - QPredGen(name: "name", myString: nil), - QPredGen(name: "name", myString: "2")] - models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myString).sortDescriptor, - modelSchema: QPredGen.schema) + var models = [ + QPredGen(name: "name", myString: "1"), + QPredGen(name: "name", myString: nil), + QPredGen(name: "name", myString: "2") + ] + models.sortModels( + by: QuerySortBy.ascending(QPredGen.keys.myString).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myString, nil) XCTAssertEqual(models[1].myString, "1") XCTAssertEqual(models[2].myString, "2") - models.sortModels(by: QuerySortBy.descending(QPredGen.keys.myString).sortDescriptor, - modelSchema: QPredGen.schema) + models.sortModels( + by: QuerySortBy.descending(QPredGen.keys.myString).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myString, "2") XCTAssertEqual(models[1].myString, "1") XCTAssertEqual(models[2].myString, nil) } func testSortModelInt() { - var models = [MutationSyncMetadata( - modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 1), - MutationSyncMetadata( - modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 2), - MutationSyncMetadata( - modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 3)] - models.sortModels(by: QuerySortBy.ascending(MutationSyncMetadata.keys.version).sortDescriptor, - modelSchema: MutationSyncMetadata.schema) + var models = [ + MutationSyncMetadata( + modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 1 + ), + MutationSyncMetadata( + modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 2 + ), + MutationSyncMetadata( + modelId: UUID().uuidString, modelName: "", deleted: false, lastChangedAt: 1, version: 3 + ) + ] + models.sortModels( + by: QuerySortBy.ascending(MutationSyncMetadata.keys.version).sortDescriptor, + modelSchema: MutationSyncMetadata.schema + ) XCTAssertEqual(models[0].version, 1) XCTAssertEqual(models[1].version, 2) XCTAssertEqual(models[2].version, 3) - models.sortModels(by: QuerySortBy.descending(MutationSyncMetadata.keys.version).sortDescriptor, - modelSchema: MutationSyncMetadata.schema) + models.sortModels( + by: QuerySortBy.descending(MutationSyncMetadata.keys.version).sortDescriptor, + modelSchema: MutationSyncMetadata.schema + ) XCTAssertEqual(models[0].version, 3) XCTAssertEqual(models[1].version, 2) XCTAssertEqual(models[2].version, 1) } func testSortModelOptionalInt() { - var models = [QPredGen(name: "name", myInt: 1), - QPredGen(name: "name", myInt: nil), - QPredGen(name: "name", myInt: 2)] + var models = [ + QPredGen(name: "name", myInt: 1), + QPredGen(name: "name", myInt: nil), + QPredGen(name: "name", myInt: 2) + ] models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myInt).sortDescriptor, modelSchema: QPredGen.schema) XCTAssertEqual(models[0].myInt, nil) XCTAssertEqual(models[1].myInt, 1) @@ -93,16 +112,22 @@ class ModelSortTests: XCTestCase { } func testSortModelOptionalDouble() { - var models = [QPredGen(name: "name", myDouble: 1.1), - QPredGen(name: "name", myDouble: nil), - QPredGen(name: "name", myDouble: 2.2)] - models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myDouble).sortDescriptor, - modelSchema: QPredGen.schema) + var models = [ + QPredGen(name: "name", myDouble: 1.1), + QPredGen(name: "name", myDouble: nil), + QPredGen(name: "name", myDouble: 2.2) + ] + models.sortModels( + by: QuerySortBy.ascending(QPredGen.keys.myDouble).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myDouble, nil) XCTAssertEqual(models[1].myDouble, 1.1) XCTAssertEqual(models[2].myDouble, 2.2) - models.sortModels(by: QuerySortBy.descending(QPredGen.keys.myDouble).sortDescriptor, - modelSchema: QPredGen.schema) + models.sortModels( + by: QuerySortBy.descending(QPredGen.keys.myDouble).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myDouble, 2.2) XCTAssertEqual(models[1].myDouble, 1.1) XCTAssertEqual(models[2].myDouble, nil) @@ -112,16 +137,22 @@ class ModelSortTests: XCTestCase { let date1 = Temporal.Date.now() let date2 = Temporal.Date.now().add(value: 1, to: .day) let date3 = Temporal.Date.now().add(value: 2, to: .day) - var models = [createModel(date: date1), - createModel(date: date2), - createModel(date: date3)] - models.sortModels(by: QuerySortBy.ascending(ExampleWithEveryType.keys.dateField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + var models = [ + createModel(date: date1), + createModel(date: date2), + createModel(date: date3) + ] + models.sortModels( + by: QuerySortBy.ascending(ExampleWithEveryType.keys.dateField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].dateField, date1) XCTAssertEqual(models[1].dateField, date2) XCTAssertEqual(models[2].dateField, date3) - models.sortModels(by: QuerySortBy.descending(ExampleWithEveryType.keys.dateField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + models.sortModels( + by: QuerySortBy.descending(ExampleWithEveryType.keys.dateField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].dateField, date3) XCTAssertEqual(models[1].dateField, date2) XCTAssertEqual(models[2].dateField, date1) @@ -130,9 +161,11 @@ class ModelSortTests: XCTestCase { func testSortModelOptionalDate() { let date1 = Temporal.Date.now().add(value: 1, to: .day) let date2 = Temporal.Date.now().add(value: 2, to: .day) - var models = [QPredGen(name: "name", myDate: date1), - QPredGen(name: "name", myDate: nil), - QPredGen(name: "name", myDate: date2)] + var models = [ + QPredGen(name: "name", myDate: date1), + QPredGen(name: "name", myDate: nil), + QPredGen(name: "name", myDate: date2) + ] models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myDate).sortDescriptor, modelSchema: QPredGen.schema) XCTAssertEqual(models[0].myDate, nil) XCTAssertEqual(models[1].myDate, date1) @@ -147,9 +180,11 @@ class ModelSortTests: XCTestCase { let dateTime1 = Temporal.DateTime.now() let dateTime2 = Temporal.DateTime.now().add(value: 1, to: .day) let dateTime3 = Temporal.DateTime.now().add(value: 2, to: .day) - var posts = [createPost(createdAt: dateTime1), - createPost(createdAt: dateTime2), - createPost(createdAt: dateTime3)] + var posts = [ + createPost(createdAt: dateTime1), + createPost(createdAt: dateTime2), + createPost(createdAt: dateTime3) + ] posts.sortModels(by: QuerySortBy.ascending(Post.keys.createdAt).sortDescriptor, modelSchema: Post.schema) XCTAssertEqual(posts[0].createdAt, dateTime1) XCTAssertEqual(posts[1].createdAt, dateTime2) @@ -163,16 +198,22 @@ class ModelSortTests: XCTestCase { func testSortModelOptionalDateTime() { let datetime1 = Temporal.DateTime.now().add(value: 1, to: .day) let datetime2 = Temporal.DateTime.now().add(value: 2, to: .day) - var models = [QPredGen(name: "name", myDateTime: datetime1), - QPredGen(name: "name", myDateTime: nil), - QPredGen(name: "name", myDateTime: datetime2)] - models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myDateTime).sortDescriptor, - modelSchema: QPredGen.schema) + var models = [ + QPredGen(name: "name", myDateTime: datetime1), + QPredGen(name: "name", myDateTime: nil), + QPredGen(name: "name", myDateTime: datetime2) + ] + models.sortModels( + by: QuerySortBy.ascending(QPredGen.keys.myDateTime).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myDateTime, nil) XCTAssertEqual(models[1].myDateTime, datetime1) XCTAssertEqual(models[2].myDateTime, datetime2) - models.sortModels(by: QuerySortBy.descending(QPredGen.keys.myDateTime).sortDescriptor, - modelSchema: QPredGen.schema) + models.sortModels( + by: QuerySortBy.descending(QPredGen.keys.myDateTime).sortDescriptor, + modelSchema: QPredGen.schema + ) XCTAssertEqual(models[0].myDateTime, datetime2) XCTAssertEqual(models[1].myDateTime, datetime1) XCTAssertEqual(models[2].myDateTime, nil) @@ -182,9 +223,11 @@ class ModelSortTests: XCTestCase { let time1 = Temporal.Time.now() let time2 = Temporal.Time.now().add(value: 2, to: .day) let time3 = Temporal.Time.now().add(value: 3, to: .day) - var models = [QPredGen(name: "name", myTime: time2), - QPredGen(name: "name", myTime: time1), - QPredGen(name: "name", myTime: time3)] + var models = [ + QPredGen(name: "name", myTime: time2), + QPredGen(name: "name", myTime: time1), + QPredGen(name: "name", myTime: time3) + ] models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myTime).sortDescriptor, modelSchema: QPredGen.schema) XCTAssertEqual(models[0].myTime, time1) @@ -200,9 +243,11 @@ class ModelSortTests: XCTestCase { func testSortModelOptionalTime() { let time1 = Temporal.Time.now().add(value: 1, to: .day) let time2 = Temporal.Time.now().add(value: 2, to: .day) - var models = [QPredGen(name: "name", myTime: time1), - QPredGen(name: "name", myTime: nil), - QPredGen(name: "name", myTime: time2)] + var models = [ + QPredGen(name: "name", myTime: time1), + QPredGen(name: "name", myTime: nil), + QPredGen(name: "name", myTime: time2) + ] models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myTime).sortDescriptor, modelSchema: QPredGen.schema) XCTAssertEqual(models[0].myTime, nil) @@ -216,25 +261,33 @@ class ModelSortTests: XCTestCase { } func testSortModelBool() { - var models = [createModel(bool: false), - createModel(bool: true), - createModel(bool: false)] - models.sortModels(by: QuerySortBy.ascending(ExampleWithEveryType.keys.boolField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + var models = [ + createModel(bool: false), + createModel(bool: true), + createModel(bool: false) + ] + models.sortModels( + by: QuerySortBy.ascending(ExampleWithEveryType.keys.boolField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].boolField, false) XCTAssertEqual(models[1].boolField, false) XCTAssertEqual(models[2].boolField, true) - models.sortModels(by: QuerySortBy.descending(ExampleWithEveryType.keys.boolField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + models.sortModels( + by: QuerySortBy.descending(ExampleWithEveryType.keys.boolField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].boolField, true) XCTAssertEqual(models[1].boolField, false) XCTAssertEqual(models[2].boolField, false) } func testSortModelOptionalBool() { - var models = [QPredGen(name: "name", myBool: true), - QPredGen(name: "name", myBool: nil), - QPredGen(name: "name", myBool: false)] + var models = [ + QPredGen(name: "name", myBool: true), + QPredGen(name: "name", myBool: nil), + QPredGen(name: "name", myBool: false) + ] models.sortModels(by: QuerySortBy.ascending(QPredGen.keys.myBool).sortDescriptor, modelSchema: QPredGen.schema) XCTAssertEqual(models[0].myBool, nil) XCTAssertEqual(models[1].myBool, false) @@ -246,26 +299,34 @@ class ModelSortTests: XCTestCase { } func testSortModelEnum() { - var models = [createModel(enum: .bar), - createModel(enum: .foo), - createModel(enum: .bar)] - models.sortModels(by: QuerySortBy.ascending(ExampleWithEveryType.keys.enumField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + var models = [ + createModel(enum: .bar), + createModel(enum: .foo), + createModel(enum: .bar) + ] + models.sortModels( + by: QuerySortBy.ascending(ExampleWithEveryType.keys.enumField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].enumField, .bar) XCTAssertEqual(models[1].enumField, .bar) XCTAssertEqual(models[2].enumField, .foo) - models.sortModels(by: QuerySortBy.descending(ExampleWithEveryType.keys.enumField).sortDescriptor, - modelSchema: ExampleWithEveryType.schema) + models.sortModels( + by: QuerySortBy.descending(ExampleWithEveryType.keys.enumField).sortDescriptor, + modelSchema: ExampleWithEveryType.schema + ) XCTAssertEqual(models[0].enumField, .foo) XCTAssertEqual(models[1].enumField, .bar) XCTAssertEqual(models[2].enumField, .bar) } func testSortModelOptionalEnum() { - var posts = [createPost(status: .draft), - createPost(status: .private), - createPost(status: .published), - createPost(status: nil)] + var posts = [ + createPost(status: .draft), + createPost(status: .private), + createPost(status: .published), + createPost(status: nil) + ] posts.sortModels(by: QuerySortBy.ascending(Post.keys.status).sortDescriptor, modelSchema: Post.schema) XCTAssertEqual(posts[0].status, nil) XCTAssertEqual(posts[1].status, .draft) @@ -282,9 +343,11 @@ class ModelSortTests: XCTestCase { let dateTime1 = Temporal.DateTime.now() let dateTime2 = Temporal.DateTime.now().add(value: 1, to: .day) let dateTime3 = Temporal.DateTime.now().add(value: 2, to: .day) - var posts = [createPost(rating: 1.0, createdAt: dateTime2), - createPost(rating: 1.0, createdAt: dateTime1), - createPost(rating: 2.0, createdAt: dateTime3)] + var posts = [ + createPost(rating: 1.0, createdAt: dateTime2), + createPost(rating: 1.0, createdAt: dateTime1), + createPost(rating: 2.0, createdAt: dateTime3) + ] posts.sortModels(by: QuerySortBy.ascending(Post.keys.rating).sortDescriptor, modelSchema: Post.schema) // overall order does not change since ratings are already in asecnding order @@ -306,34 +369,44 @@ class ModelSortTests: XCTestCase { // MARK: - Helpers - func createPost(id: String = UUID().uuidString, - draft: Bool = false, - rating: Double = 1.0, - createdAt: Temporal.DateTime = .now(), - status: PostStatus? = .draft) -> Post { - Post(id: id, - title: "A", - content: "content", - createdAt: createdAt, - updatedAt: .now(), - draft: draft, - rating: rating, - status: status, - comments: nil) + func createPost( + id: String = UUID().uuidString, + draft: Bool = false, + rating: Double = 1.0, + createdAt: Temporal.DateTime = .now(), + status: PostStatus? = .draft + ) -> Post { + Post( + id: id, + title: "A", + content: "content", + createdAt: createdAt, + updatedAt: .now(), + draft: draft, + rating: rating, + status: status, + comments: nil + ) } - func createModel(date: Temporal.Date = .now(), - bool: Bool = false, - enum: ExampleEnum = .bar) -> ExampleWithEveryType { - ExampleWithEveryType(id: UUID().uuidString, - stringField: "string", - intField: 1, - doubleField: 1.0, - boolField: bool, - dateField: date, - enumField: `enum`, - nonModelField: .init(someString: "some string", - someEnum: .bar), - arrayOfStringsField: []) + func createModel( + date: Temporal.Date = .now(), + bool: Bool = false, + enum: ExampleEnum = .bar + ) -> ExampleWithEveryType { + ExampleWithEveryType( + id: UUID().uuidString, + stringField: "string", + intField: 1, + doubleField: 1.0, + boolField: bool, + dateField: date, + enumField: `enum`, + nonModelField: .init( + someString: "some string", + someEnum: .bar + ), + arrayOfStringsField: [] + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/SortedListTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/SortedListTests.swift index 48dd62f55e..511b9229e9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/SortedListTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/Support/SortedListTests.swift @@ -5,25 +5,29 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class SortedListTests: XCTestCase { func testSortedListSetAndReset() { - let posts = [createPost(id: "1", rating: 5.0), - createPost(id: "2", rating: 5.0), - createPost(id: "3", rating: 5.0), - createPost(id: "4", rating: 5.0)] - - let list = SortedList(sortInput: [QuerySortBy.ascending(Post.keys.rating).sortDescriptor], - modelSchema: Post.schema) + let posts = [ + createPost(id: "1", rating: 5.0), + createPost(id: "2", rating: 5.0), + createPost(id: "3", rating: 5.0), + createPost(id: "4", rating: 5.0) + ] + + let list = SortedList( + sortInput: [QuerySortBy.ascending(Post.keys.rating).sortDescriptor], + modelSchema: Post.schema + ) list.set(sortedModels: posts) assertPosts(list.sortedModels, expectedIds: ["1", "2", "3", "4"]) @@ -35,13 +39,17 @@ class SortedListTests: XCTestCase { } func testSortedListSingleSort() { - let posts = [createPost(id: "1"), - createPost(id: "2"), - createPost(id: "5"), - createPost(id: "6")] + let posts = [ + createPost(id: "1"), + createPost(id: "2"), + createPost(id: "5"), + createPost(id: "6") + ] let sortInput = [QuerySortBy.ascending(Post.keys.id).sortDescriptor] - let list = SortedList(sortInput: sortInput, - modelSchema: Post.schema) + let list = SortedList( + sortInput: sortInput, + modelSchema: Post.schema + ) list.set(sortedModels: posts) @@ -81,14 +89,20 @@ class SortedListTests: XCTestCase { } func testSortedListMultipleSort() { - let posts = [createPost(id: "1", rating: 5.0), - createPost(id: "2", rating: 10.0), - createPost(id: "6", rating: 10.0), - createPost(id: "5", rating: 20.0)] - let sortInput = [QuerySortBy.ascending(Post.keys.rating).sortDescriptor, - QuerySortBy.ascending(Post.keys.id).sortDescriptor] - let list = SortedList(sortInput: sortInput, - modelSchema: Post.schema) + let posts = [ + createPost(id: "1", rating: 5.0), + createPost(id: "2", rating: 10.0), + createPost(id: "6", rating: 10.0), + createPost(id: "5", rating: 20.0) + ] + let sortInput = [ + QuerySortBy.ascending(Post.keys.rating).sortDescriptor, + QuerySortBy.ascending(Post.keys.id).sortDescriptor + ] + let list = SortedList( + sortInput: sortInput, + modelSchema: Post.schema + ) list.set(sortedModels: posts) // After id: "1", rating: 5.0 @@ -120,14 +134,18 @@ class SortedListTests: XCTestCase { } func testSortedListAllEqual() { - let posts = [createPost(id: "1", rating: 5.0), - createPost(id: "2", rating: 5.0), - createPost(id: "3", rating: 5.0), - createPost(id: "4", rating: 5.0)] + let posts = [ + createPost(id: "1", rating: 5.0), + createPost(id: "2", rating: 5.0), + createPost(id: "3", rating: 5.0), + createPost(id: "4", rating: 5.0) + ] let sortInput = [QuerySortBy.ascending(Post.keys.rating).sortDescriptor] - let list = SortedList(sortInput: [QuerySortBy.ascending(Post.keys.rating).sortDescriptor], - modelSchema: Post.schema) + let list = SortedList( + sortInput: [QuerySortBy.ascending(Post.keys.rating).sortDescriptor], + modelSchema: Post.schema + ) list.set(sortedModels: posts) // Since this is a binary search, the first index where the predicate returns `nil` is the middle index @@ -149,19 +167,23 @@ class SortedListTests: XCTestCase { XCTAssertEqual(post.rating, rating) } - func createPost(id: String = UUID().uuidString, - draft: Bool = false, - rating: Double = 1.0, - createdAt: Temporal.DateTime = .now(), - status: PostStatus? = .draft) -> Post { - Post(id: id, - title: "A", - content: "content", - createdAt: createdAt, - updatedAt: .now(), - draft: draft, - rating: rating, - status: status, - comments: nil) + func createPost( + id: String = UUID().uuidString, + draft: Bool = false, + rating: Double = 1.0, + createdAt: Temporal.DateTime = .now(), + status: PostStatus? = .draft + ) -> Post { + Post( + id: id, + title: "A", + content: "content", + createdAt: createdAt, + updatedAt: .now(), + draft: draft, + rating: rating, + status: status, + comments: nil + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/APICategoryDependencyTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/APICategoryDependencyTests.swift index c578764c7c..f68ca5b877 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/APICategoryDependencyTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/APICategoryDependencyTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -62,25 +62,31 @@ extension APICategoryDependencyTests { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - let syncEngine = try RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault()) + let syncEngine = try RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault() + ) let validAPIPluginKey = "MockAPICategoryPlugin" let validAuthPluginKey = "MockAuthCategoryPlugin" - let storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let storageEngineBehaviorFactory: StorageEngineBehaviorFactory = {_, _, _, _, _, _ throws in return storageEngine } let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) try Amplify.add(plugin: dataStorePlugin) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationSyncExpressionTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationSyncExpressionTests.swift index e118693987..da1713986a 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationSyncExpressionTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationSyncExpressionTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import SQLite import Combine +import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -34,16 +34,22 @@ class InitialSyncOperationSyncExpressionTests: XCTestCase { apiWasQueried = expectation(description: "API was queried with sync expression") } - func initialSyncOperation(withSyncExpression syncExpression: DataStoreSyncExpression, - responder: APIPluginQueryResponder) -> InitialSyncOperation { + func initialSyncOperation( + withSyncExpression syncExpression: DataStoreSyncExpression, + responder: APIPluginQueryResponder + ) -> InitialSyncOperation { apiPlugin.responders[.queryRequestResponse] = responder #if os(watchOS) - let configuration = DataStoreConfiguration.custom(syncPageSize: 10, - syncExpressions: [syncExpression], - disableSubscriptions: { false }) + let configuration = DataStoreConfiguration.custom( + syncPageSize: 10, + syncExpressions: [syncExpression], + disableSubscriptions: { false } + ) #else - let configuration = DataStoreConfiguration.custom(syncPageSize: 10, - syncExpressions: [syncExpression]) + let configuration = DataStoreConfiguration.custom( + syncPageSize: 10, + syncExpressions: [syncExpression] + ) #endif return InitialSyncOperation( modelSchema: MockSynced.schema, @@ -51,7 +57,8 @@ class InitialSyncOperationSyncExpressionTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: configuration, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) } func testBaseQueryWithBasicSyncExpression() async throws { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift index 07cdd95ecb..de12a9357d 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import SQLite import Combine +import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -25,7 +25,7 @@ class InitialSyncOperationTests: XCTestCase { // MARK: - GetLastSyncTime func testFullSyncWhenLastSyncPredicateNilAndCurrentSyncPredicateNonNil() async { - let lastSyncTime: Int64 = 123456 + let lastSyncTime: Int64 = 123_456 let lastSyncPredicate: String? = nil let currentSyncPredicate: DataStoreConfiguration #if os(watchOS) @@ -59,7 +59,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: nil, storageAdapter: nil, dataStoreConfiguration: currentSyncPredicate, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let sink = operation .publisher .sink(receiveCompletion: { _ in @@ -74,9 +75,11 @@ class InitialSyncOperationTests: XCTestCase { } }) - let lastSyncMetadataLastSyncNil = ModelSyncMetadata(id: MockSynced.schema.name, - lastSync: lastSyncTime, - syncPredicate: lastSyncPredicate) + let lastSyncMetadataLastSyncNil = ModelSyncMetadata( + id: MockSynced.schema.name, + lastSync: lastSyncTime, + syncPredicate: lastSyncPredicate + ) XCTAssertEqual(operation.getLastSyncTime(lastSyncMetadataLastSyncNil), expectedLastSync) await fulfillment(of: [syncStartedReceived], timeout: 1) @@ -84,7 +87,7 @@ class InitialSyncOperationTests: XCTestCase { } func testFullSyncWhenLastSyncPredicateNonNilAndCurrentSyncPredicateNil() async { - let lastSyncTime: Int64 = 123456 + let lastSyncTime: Int64 = 123_456 let lastSyncPredicate: String? = "non nil" let expectedSyncType = SyncType.fullSync let expectedLastSync: Int64? = nil @@ -96,7 +99,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: nil, storageAdapter: nil, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let sink = operation .publisher .sink(receiveCompletion: { _ in @@ -111,9 +115,11 @@ class InitialSyncOperationTests: XCTestCase { } }) - let lastSyncMetadataLastSyncNil = ModelSyncMetadata(id: MockSynced.schema.name, - lastSync: lastSyncTime, - syncPredicate: lastSyncPredicate) + let lastSyncMetadataLastSyncNil = ModelSyncMetadata( + id: MockSynced.schema.name, + lastSync: lastSyncTime, + syncPredicate: lastSyncPredicate + ) XCTAssertEqual(operation.getLastSyncTime(lastSyncMetadataLastSyncNil), expectedLastSync) await fulfillment(of: [syncStartedReceived], timeout: 1) @@ -121,7 +127,7 @@ class InitialSyncOperationTests: XCTestCase { } func testFullSyncWhenLastSyncPredicateDifferentFromCurrentSyncPredicate() async { - let lastSyncTime: Int64 = 123456 + let lastSyncTime: Int64 = 123_456 let lastSyncPredicate: String? = "non nil different from current predicate" let currentSyncPredicate: DataStoreConfiguration #if os(watchOS) @@ -155,7 +161,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: nil, storageAdapter: nil, dataStoreConfiguration: currentSyncPredicate, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let sink = operation .publisher .sink(receiveCompletion: { _ in @@ -170,9 +177,11 @@ class InitialSyncOperationTests: XCTestCase { } }) - let lastSyncMetadataLastSyncNil = ModelSyncMetadata(id: MockSynced.schema.name, - lastSync: lastSyncTime, - syncPredicate: lastSyncPredicate) + let lastSyncMetadataLastSyncNil = ModelSyncMetadata( + id: MockSynced.schema.name, + lastSync: lastSyncTime, + syncPredicate: lastSyncPredicate + ) XCTAssertEqual(operation.getLastSyncTime(lastSyncMetadataLastSyncNil), expectedLastSync) await fulfillment(of: [syncStartedReceived], timeout: 1) @@ -215,7 +224,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: nil, storageAdapter: nil, dataStoreConfiguration: currentSyncPredicate, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let sink = operation .publisher .sink(receiveCompletion: { _ in @@ -230,9 +240,11 @@ class InitialSyncOperationTests: XCTestCase { } }) - let lastSyncMetadataLastSyncNil = ModelSyncMetadata(id: MockSynced.schema.name, - lastSync: lastSyncTime, - syncPredicate: lastSyncPredicate) + let lastSyncMetadataLastSyncNil = ModelSyncMetadata( + id: MockSynced.schema.name, + lastSync: lastSyncTime, + syncPredicate: lastSyncPredicate + ) XCTAssertEqual(operation.getLastSyncTime(lastSyncMetadataLastSyncNil), expectedLastSync) await fulfillment(of: [syncStartedReceived], timeout: 1) @@ -269,7 +281,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -326,7 +339,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -381,7 +395,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") let finishedReceived = expectation(description: "InitialSyncOperation finished paginating and offering") @@ -436,7 +451,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") let finishedReceived = expectation(description: "InitialSyncOperation finished paginating and offering") @@ -468,11 +484,13 @@ class InitialSyncOperationTests: XCTestCase { let startedAtMilliseconds = Int64(Date().timeIntervalSince1970) * 1_000 let model = MockSynced(id: "1") let anyModel = AnyModel(model) - let metadata = MutationSyncMetadata(modelId: "1", - modelName: MockSynced.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let metadata = MutationSyncMetadata( + modelId: "1", + modelName: MockSynced.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let mutationSync = MutationSync(model: anyModel, syncMetadata: metadata) let responder = QueryRequestResponder> { _ in let list = PaginatedList(items: [mutationSync], nextToken: nil, startedAt: startedAtMilliseconds) @@ -501,7 +519,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -560,7 +579,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -620,14 +640,16 @@ class InitialSyncOperationTests: XCTestCase { #if os(watchOS) let configuration = DataStoreConfiguration.custom(errorHandler: { error in guard let dataStoreError = error as? DataStoreError, - case let .api(amplifyError, mutationEventOptional) = dataStoreError else { + case let .api(amplifyError, mutationEventOptional) = dataStoreError + else { XCTFail("Expected API error with mutationEvent") return } guard let actualAPIError = amplifyError as? APIError, case let .operationError(_, _, underlyingError) = actualAPIError, let authError = underlyingError as? AuthError, - case .signedOut = authError else { + case .signedOut = authError + else { XCTFail("Should be `signedOut` error but got \(amplifyError)") return } @@ -637,14 +659,16 @@ class InitialSyncOperationTests: XCTestCase { #else let configuration = DataStoreConfiguration.custom(errorHandler: { error in guard let dataStoreError = error as? DataStoreError, - case let .api(amplifyError, mutationEventOptional) = dataStoreError else { + case let .api(amplifyError, mutationEventOptional) = dataStoreError + else { XCTFail("Expected API error with mutationEvent") return } guard let actualAPIError = amplifyError as? APIError, case let .operationError(_, _, underlyingError) = actualAPIError, let authError = underlyingError as? AuthError, - case .signedOut = authError else { + case .signedOut = authError + else { XCTFail("Should be `signedOut` error but got \(amplifyError)") return } @@ -658,7 +682,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: configuration, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -744,7 +769,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -818,7 +844,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: configuration, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -880,7 +907,8 @@ class InitialSyncOperationTests: XCTestCase { reconciliationQueue: reconciliationQueue, storageAdapter: storageAdapter, dataStoreConfiguration: configuration, - authModeStrategy: AWSDefaultAuthModeStrategy()) + authModeStrategy: AWSDefaultAuthModeStrategy() + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") let syncCompletionReceived = expectation(description: "Sync completion received, sync operation is complete") @@ -906,12 +934,15 @@ class InitialSyncOperationTests: XCTestCase { operation.main() - await fulfillment(of: [ - syncStartedReceived, - syncCompletionReceived, - finishedReceived, - apiWasQueried], - timeout: 1) + await fulfillment( + of: [ + syncStartedReceived, + syncCompletionReceived, + finishedReceived, + apiWasQueried + ], + timeout: 1 + ) sink.cancel() } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift index 1e4a7ca208..a177f57beb 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Foundation +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -41,12 +41,14 @@ class InitialSyncOrchestratorTests: XCTestCase { let reconciliationQueue = MockReconciliationQueue() - let orchestrator: AWSInitialSyncOrchestrator = - AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + let orchestrator = + AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) let syncCallbackReceived = expectation(description: "Sync callback received, sync operation is complete") let syncQueriesStartedReceived = expectation(description: "syncQueriesStarted received") @@ -109,7 +111,7 @@ class InitialSyncOrchestratorTests: XCTestCase { Amplify.Hub.removeListener(hubListener) sink.cancel() } - + /// - Given: An InitialSyncOrchestrator with a model dependency graph, API is expected to return an error for certain models /// - When: /// - The orchestrator starts up @@ -137,12 +139,14 @@ class InitialSyncOrchestratorTests: XCTestCase { let reconciliationQueue = MockReconciliationQueue() - let orchestrator: AWSInitialSyncOrchestrator = - AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + let orchestrator = + AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) let syncCallbackReceived = expectation(description: "Sync callback received, sync operation is complete") let syncQueriesStartedReceived = expectation(description: "syncQueriesStarted received") @@ -213,7 +217,7 @@ class InitialSyncOrchestratorTests: XCTestCase { Amplify.Hub.removeListener(hubListener) sink.cancel() } - + /// - Given: An InitialSyncOrchestrator with a model dependency graph containing no associations /// - When: /// - The orchestrator starts up @@ -246,11 +250,13 @@ class InitialSyncOrchestratorTests: XCTestCase { let reconciliationQueue = MockReconciliationQueue() - let orchestrator = AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + let orchestrator = AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) let syncCallbackReceived = expectation(description: "Sync callback received, sync operation is complete") let syncStartedReceived = expectation(description: "Sync started received, sync operation started") syncStartedReceived.expectedFulfillmentCount = 2 @@ -258,8 +264,9 @@ class InitialSyncOrchestratorTests: XCTestCase { finishedReceived.expectedFulfillmentCount = 2 let sink = orchestrator .publisher - .sink(receiveCompletion: { _ in }, - receiveValue: { value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { value in switch value { case .started: syncStartedReceived.fulfill() @@ -268,7 +275,8 @@ class InitialSyncOrchestratorTests: XCTestCase { default: break } - }) + } + ) orchestrator.sync { _ in syncCallbackReceived.fulfill() @@ -311,12 +319,14 @@ class InitialSyncOrchestratorTests: XCTestCase { let reconciliationQueue = MockReconciliationQueue() - let orchestrator: AWSInitialSyncOrchestrator = - AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + let orchestrator = + AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") syncStartedReceived.expectedFulfillmentCount = 2 @@ -324,8 +334,9 @@ class InitialSyncOrchestratorTests: XCTestCase { finishedReceived.expectedFulfillmentCount = 2 let sink = orchestrator .publisher - .sink(receiveCompletion: { _ in }, - receiveValue: { value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { value in switch value { case .started: syncStartedReceived.fulfill() @@ -334,7 +345,8 @@ class InitialSyncOrchestratorTests: XCTestCase { default: break } - }) + } + ) orchestrator.sync { _ in } @@ -384,12 +396,14 @@ class InitialSyncOrchestratorTests: XCTestCase { let reconciliationQueue = MockReconciliationQueue() - let orchestrator: AWSInitialSyncOrchestrator = - AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + let orchestrator = + AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) let syncStartedReceived = expectation(description: "Sync started received, sync operation started") syncStartedReceived.expectedFulfillmentCount = 2 @@ -397,8 +411,9 @@ class InitialSyncOrchestratorTests: XCTestCase { finishedReceived.expectedFulfillmentCount = 2 let sink = orchestrator .publisher - .sink(receiveCompletion: { _ in }, - receiveValue: { value in + .sink( + receiveCompletion: { _ in }, + receiveValue: { value in switch value { case .started: syncStartedReceived.fulfill() @@ -407,7 +422,8 @@ class InitialSyncOrchestratorTests: XCTestCase { default: break } - }) + } + ) orchestrator.sync { _ in } @@ -427,35 +443,43 @@ class InitialSyncOrchestratorTests: XCTestCase { let apiPlugin = MockAPICategoryPlugin() let storageAdapter = MockSQLiteStorageEngineAdapter() let reconciliationQueue = MockReconciliationQueue() - + let orchestrator = - AWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - api: apiPlugin, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) - - let error1 = DataStoreError.api(APIError.httpStatusError(401, HTTPURLResponse(url: URL(string: "https://aws.amazon.com")!, - statusCode: 401, - httpVersion: nil, - headerFields: nil)!)) + AWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + api: apiPlugin, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) + + let error1 = DataStoreError.api(APIError.httpStatusError(401, HTTPURLResponse( + url: URL(string: "https://aws.amazon.com")!, + statusCode: 401, + httpVersion: nil, + headerFields: nil + )!)) XCTAssertTrue(orchestrator.isUnauthorizedError(DataStoreError.sync("", "", error1))) - - let error2 = DataStoreError.api(APIError.httpStatusError(403, HTTPURLResponse(url: URL(string: "https://aws.amazon.com")!, - statusCode: 403, - httpVersion: nil, - headerFields: nil)!)) + + let error2 = DataStoreError.api(APIError.httpStatusError(403, HTTPURLResponse( + url: URL(string: "https://aws.amazon.com")!, + statusCode: 403, + httpVersion: nil, + headerFields: nil + )!)) XCTAssertTrue(orchestrator.isUnauthorizedError(DataStoreError.sync("", "", error2))) - - let error3 = DataStoreError.api(APIError.httpStatusError(404, HTTPURLResponse(url: URL(string: "https://aws.amazon.com")!, - statusCode: 404, - httpVersion: nil, - headerFields: nil)!)) + + let error3 = DataStoreError.api(APIError.httpStatusError(404, HTTPURLResponse( + url: URL(string: "https://aws.amazon.com")!, + statusCode: 404, + httpVersion: nil, + headerFields: nil + )!)) XCTAssertFalse(orchestrator.isUnauthorizedError(DataStoreError.sync("", "", error3))) - + let error4 = DataStoreError.api(APIError.operationError("Unauthorized error", "", nil)) XCTAssertTrue(orchestrator.isUnauthorizedError(DataStoreError.sync("", "", error4))) - + let error5 = DataStoreError.api(APIError.operationError("An error occurred", "", nil)) XCTAssertFalse(orchestrator.isUnauthorizedError(DataStoreError.sync("", "", error5))) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ModelSyncedEventEmitterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ModelSyncedEventEmitterTests.swift index d3ee5e1a1b..7ce773e356 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ModelSyncedEventEmitterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ModelSyncedEventEmitterTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class ModelSyncedEventEmitterTests: XCTestCase { @@ -20,15 +20,19 @@ class ModelSyncedEventEmitterTests: XCTestCase { var reconciliationQueue: MockAWSIncomingEventReconciliationQueue? override func setUp() { - initialSyncOrchestrator = MockAWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - api: nil, - reconciliationQueue: nil, - storageAdapter: nil) - reconciliationQueue = MockAWSIncomingEventReconciliationQueue(modelSchemas: [Post.schema], - api: nil, - storageAdapter: nil, - syncExpressions: [], - auth: nil) + initialSyncOrchestrator = MockAWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + api: nil, + reconciliationQueue: nil, + storageAdapter: nil + ) + reconciliationQueue = MockAWSIncomingEventReconciliationQueue( + modelSchemas: [Post.schema], + api: nil, + storageAdapter: nil, + syncExpressions: [], + auth: nil + ) ModelRegistry.register(modelType: Post.self) } @@ -46,11 +50,13 @@ class ModelSyncedEventEmitterTests: XCTestCase { mutationEventAppliedReceived.expectedFulfillmentCount = 3 let mutationEventDroppedReceived = expectation(description: "mutationEventDropped received") mutationEventDroppedReceived.expectedFulfillmentCount = 2 - let anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: Post.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: Post.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) let anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) @@ -58,9 +64,11 @@ class ModelSyncedEventEmitterTests: XCTestCase { var receivedMutationEventsCount = 0 var modelSyncedEventReceivedLast = false - let emitter = ModelSyncedEventEmitter(modelSchema: Post.schema, - initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + let emitter = ModelSyncedEventEmitter( + modelSchema: Post.schema, + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) var emitterSink: AnyCancellable? emitterSink = emitter.publisher.sink { _ in @@ -68,12 +76,14 @@ class ModelSyncedEventEmitterTests: XCTestCase { } receiveValue: { value in switch value { case .modelSyncedEvent(let modelSyncedEvent): - let expectedModelSyncedEventPayload = ModelSyncedEvent(modelName: "Post", - isFullSync: true, - isDeltaSync: false, - added: 3, - updated: 0, - deleted: 0) + let expectedModelSyncedEventPayload = ModelSyncedEvent( + modelName: "Post", + isFullSync: true, + isDeltaSync: false, + added: 3, + updated: 0, + deleted: 0 + ) XCTAssertEqual(modelSyncedEvent, expectedModelSyncedEventPayload) if receivedMutationEventsCount == 5 { modelSyncedEventReceivedLast = true @@ -88,18 +98,30 @@ class ModelSyncedEventEmitterTests: XCTestCase { } } - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Post.modelName, - syncType: .fullSync)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Post.modelName, + syncType: .fullSync + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.finished(modelName: Post.modelName)) reconciliationQueue?.incomingEventSubject.send(.mutationEventApplied(postMutationEvent)) reconciliationQueue?.incomingEventSubject.send(.mutationEventDropped(modelName: Post.modelName)) @@ -126,18 +148,22 @@ class ModelSyncedEventEmitterTests: XCTestCase { mutationEventAppliedReceived.expectedFulfillmentCount = 5 let mutationEventDroppedReceived = expectation(description: "mutationEventDropped received") mutationEventDroppedReceived.expectedFulfillmentCount = 3 - let anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: "", - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: "", + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) let anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) let postMutationEvent = try MutationEvent(untypedModel: testPost, mutationType: .create) - let emitter = ModelSyncedEventEmitter(modelSchema: Post.schema, - initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + let emitter = ModelSyncedEventEmitter( + modelSchema: Post.schema, + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) var emitterSink: AnyCancellable? emitterSink = emitter.publisher.sink { _ in @@ -145,12 +171,14 @@ class ModelSyncedEventEmitterTests: XCTestCase { } receiveValue: { value in switch value { case .modelSyncedEvent(let modelSyncedEvent): - let expectedModelSyncedEventPayload = ModelSyncedEvent(modelName: "Post", - isFullSync: true, - isDeltaSync: false, - added: 2, - updated: 0, - deleted: 0) + let expectedModelSyncedEventPayload = ModelSyncedEvent( + modelName: "Post", + isFullSync: true, + isDeltaSync: false, + added: 2, + updated: 0, + deleted: 0 + ) XCTAssertEqual(modelSyncedEvent, expectedModelSyncedEventPayload) modelSyncedReceived.fulfill() case .mutationEventApplied: @@ -160,12 +188,18 @@ class ModelSyncedEventEmitterTests: XCTestCase { } } - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Post.modelName, - syncType: .fullSync)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Post.modelName, + syncType: .fullSync + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.finished(modelName: Post.modelName)) reconciliationQueue?.incomingEventSubject.send(.mutationEventApplied(postMutationEvent)) reconciliationQueue?.incomingEventSubject.send(.mutationEventApplied(postMutationEvent)) @@ -199,22 +233,28 @@ class ModelSyncedEventEmitterTests: XCTestCase { mutationEventAppliedReceived.assertForOverFulfill = false let mutationEventDroppedReceived = expectation(description: "mutationEventDropped received") mutationEventDroppedReceived.assertForOverFulfill = false - let anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: Post.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: Post.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) let anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) let postMutationEvent = try MutationEvent(untypedModel: testPost, mutationType: .create) - let emitter = ModelSyncedEventEmitter(modelSchema: Post.schema, - initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + let emitter = ModelSyncedEventEmitter( + modelSchema: Post.schema, + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Post.modelName, - syncType: .fullSync)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Post.modelName, + syncType: .fullSync + )) DispatchQueue.concurrentPerform(iterations: 1_000) { _ in let index = Int.random(in: 1 ... 10) if index == 1 { @@ -222,8 +262,10 @@ class ModelSyncedEventEmitterTests: XCTestCase { } else if index == 2 { reconciliationQueue?.incomingEventSubject.send(.mutationEventDropped(modelName: Post.modelName)) } else { - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift index 9d105456e1..c19590406c 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation -import XCTest import SQLite -import Combine +import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class ReadyEventEmitterTests: XCTestCase { var stateMachine: MockStateMachine! diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/SyncEventEmitterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/SyncEventEmitterTests.swift index 09b3177891..5ed6e24569 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/SyncEventEmitterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/SyncEventEmitterTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class SyncEventEmitterTests: XCTestCase { var initialSyncOrchestrator: MockAWSInitialSyncOrchestrator? @@ -42,27 +42,35 @@ class SyncEventEmitterTests: XCTestCase { ModelRegistry.register(modelType: Post.self) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) - let anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: Post.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: Post.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) let postMutationEvent = try MutationEvent(untypedModel: testPost, mutationType: .create) - reconciliationQueue = MockAWSIncomingEventReconciliationQueue(modelSchemas: [Post.schema], - api: nil, - storageAdapter: nil, - syncExpressions: [], - auth: nil) - - initialSyncOrchestrator = MockAWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - api: nil, - reconciliationQueue: nil, - storageAdapter: nil) - - syncEventEmitter = SyncEventEmitter(initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + reconciliationQueue = MockAWSIncomingEventReconciliationQueue( + modelSchemas: [Post.schema], + api: nil, + storageAdapter: nil, + syncExpressions: [], + auth: nil + ) + + initialSyncOrchestrator = MockAWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + api: nil, + reconciliationQueue: nil, + storageAdapter: nil + ) + + syncEventEmitter = SyncEventEmitter( + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) var syncEventEmitterSink: AnyCancellable? syncEventEmitterSink = syncEventEmitter?.publisher.sink(receiveCompletion: { completion in XCTFail("Should not have completed: \(completion)") @@ -73,9 +81,14 @@ class SyncEventEmitterTests: XCTestCase { case .mutationEventDropped: break case .modelSyncedEvent(let modelSyncedEvent): - let expectedModelSyncedEventPayload = ModelSyncedEvent(modelName: "Post", - isFullSync: true, isDeltaSync: false, - added: 1, updated: 0, deleted: 0) + let expectedModelSyncedEventPayload = ModelSyncedEvent( + modelName: "Post", + isFullSync: true, + isDeltaSync: false, + added: 1, + updated: 0, + deleted: 0 + ) XCTAssertTrue(modelSyncedEvent == expectedModelSyncedEventPayload) modelSyncedReceived.fulfill() case .syncQueriesReadyEvent: @@ -83,10 +96,14 @@ class SyncEventEmitterTests: XCTestCase { } }) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Post.modelName, - syncType: .fullSync)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Post.modelName, + syncType: .fullSync + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.finished(modelName: Post.modelName)) reconciliationQueue?.incomingEventSubject.send(.mutationEventApplied(postMutationEvent)) @@ -116,28 +133,46 @@ class SyncEventEmitterTests: XCTestCase { var modelSyncedEventPayloads = [ModelSyncedEvent]() let expectedModelSyncedEventPayloads: [ModelSyncedEvent] - = [ModelSyncedEvent(modelName: "Comment", - isFullSync: true, isDeltaSync: false, - added: 0, updated: 0, deleted: 0), - ModelSyncedEvent(modelName: "Post", - isFullSync: true, isDeltaSync: false, - added: 0, updated: 0, deleted: 0)] - - let syncableModelSchemas = ModelRegistry.modelSchemas.filter { $0.isSyncable } - - reconciliationQueue = MockAWSIncomingEventReconciliationQueue(modelSchemas: syncableModelSchemas, - api: nil, - storageAdapter: nil, - syncExpressions: [], - auth: nil) - - initialSyncOrchestrator = MockAWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - api: nil, - reconciliationQueue: nil, - storageAdapter: nil) - - syncEventEmitter = SyncEventEmitter(initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + = [ + ModelSyncedEvent( + modelName: "Comment", + isFullSync: true, + isDeltaSync: false, + added: 0, + updated: 0, + deleted: 0 + ), + ModelSyncedEvent( + modelName: "Post", + isFullSync: true, + isDeltaSync: false, + added: 0, + updated: 0, + deleted: 0 + ) + ] + + let syncableModelSchemas = ModelRegistry.modelSchemas.filter(\.isSyncable) + + reconciliationQueue = MockAWSIncomingEventReconciliationQueue( + modelSchemas: syncableModelSchemas, + api: nil, + storageAdapter: nil, + syncExpressions: [], + auth: nil + ) + + initialSyncOrchestrator = MockAWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + api: nil, + reconciliationQueue: nil, + storageAdapter: nil + ) + + syncEventEmitter = SyncEventEmitter( + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) var syncEventEmitterSink: AnyCancellable? syncEventEmitterSink = syncEventEmitter?.publisher.sink(receiveCompletion: { completion in @@ -193,49 +228,71 @@ class SyncEventEmitterTests: XCTestCase { ModelRegistry.register(modelType: Comment.self) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) - let anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: Post.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: Post.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) let postMutationEvent = try MutationEvent(untypedModel: testPost, mutationType: .create) let testComment = Comment(id: "1", content: "content", createdAt: .now(), post: testPost) let anyComment = AnyModel(testComment) - let anyCommentMetadata = MutationSyncMetadata(modelId: "1", - modelName: Comment.modelName, - deleted: true, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 2) + let anyCommentMetadata = MutationSyncMetadata( + modelId: "1", + modelName: Comment.modelName, + deleted: true, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 2 + ) let anyCommentMutationSync = MutationSync(model: anyComment, syncMetadata: anyCommentMetadata) let commentMutationEvent = try MutationEvent(untypedModel: testComment, mutationType: .delete) let expectedModelSyncedEventPayloads: [ModelSyncedEvent] - = [ModelSyncedEvent(modelName: "Comment", - isFullSync: true, isDeltaSync: false, - added: 0, updated: 0, deleted: 1), - ModelSyncedEvent(modelName: "Post", - isFullSync: true, isDeltaSync: false, - added: 1, updated: 0, deleted: 0)] + = [ + ModelSyncedEvent( + modelName: "Comment", + isFullSync: true, + isDeltaSync: false, + added: 0, + updated: 0, + deleted: 1 + ), + ModelSyncedEvent( + modelName: "Post", + isFullSync: true, + isDeltaSync: false, + added: 1, + updated: 0, + deleted: 0 + ) + ] var modelSyncedEventPayloads = [ModelSyncedEvent]() - let syncableModelSchemas = ModelRegistry.modelSchemas.filter { $0.isSyncable } + let syncableModelSchemas = ModelRegistry.modelSchemas.filter(\.isSyncable) - reconciliationQueue = MockAWSIncomingEventReconciliationQueue(modelSchemas: syncableModelSchemas, - api: nil, - storageAdapter: nil, - syncExpressions: [], - auth: nil) + reconciliationQueue = MockAWSIncomingEventReconciliationQueue( + modelSchemas: syncableModelSchemas, + api: nil, + storageAdapter: nil, + syncExpressions: [], + auth: nil + ) - initialSyncOrchestrator = MockAWSInitialSyncOrchestrator(dataStoreConfiguration: .testDefault(), - api: nil, - reconciliationQueue: nil, - storageAdapter: nil) + initialSyncOrchestrator = MockAWSInitialSyncOrchestrator( + dataStoreConfiguration: .testDefault(), + api: nil, + reconciliationQueue: nil, + storageAdapter: nil + ) - syncEventEmitter = SyncEventEmitter(initialSyncOrchestrator: initialSyncOrchestrator, - reconciliationQueue: reconciliationQueue) + syncEventEmitter = SyncEventEmitter( + initialSyncOrchestrator: initialSyncOrchestrator, + reconciliationQueue: reconciliationQueue + ) var syncEventEmitterSink: AnyCancellable? syncEventEmitterSink = syncEventEmitter?.publisher.sink(receiveCompletion: { completion in @@ -262,16 +319,24 @@ class SyncEventEmitterTests: XCTestCase { } }) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Post.modelName, - syncType: .fullSync)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyPostMutationSync, - modelName: Post.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Post.modelName, + syncType: .fullSync + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyPostMutationSync, + modelName: Post.modelName + )) initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.finished(modelName: Post.modelName)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started(modelName: Comment.modelName, - syncType: .fullSync)) - initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued(anyCommentMutationSync, - modelName: Comment.modelName)) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.started( + modelName: Comment.modelName, + syncType: .fullSync + )) + initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.enqueued( + anyCommentMutationSync, + modelName: Comment.modelName + )) initialSyncOrchestrator?.initialSyncOrchestratorTopic.send(.finished(modelName: Comment.modelName)) reconciliationQueue?.incomingEventSubject.send(.mutationEventApplied(postMutationEvent)) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionTests.swift index 13d8333dc5..1f0212559e 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest import Combine @testable import Amplify -@testable import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import AWSPluginsCore /// Tests behavior of local DataStore subscriptions (as opposed to remote API subscription behaviors) class LocalSubscriptionTests: XCTestCase { @@ -36,8 +36,10 @@ class LocalSubscriptionTests: XCTestCase { let outgoingMutationQueue = NoOpMutationQueue() let mutationDatabaseAdapter = try AWSMutationDatabaseAdapter(storageAdapter: storageAdapter) let awsMutationEventPublisher = AWSMutationEventPublisher(eventSource: mutationDatabaseAdapter) - stateMachine = MockStateMachine(initialState: .notStarted, - resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:)) + stateMachine = MockStateMachine( + initialState: .notStarted, + resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:) + ) let syncEngine = RemoteSyncEngine( storageAdapter: storageAdapter, @@ -53,11 +55,13 @@ class LocalSubscriptionTests: XCTestCase { requestRetryablePolicy: MockRequestRetryablePolicy() ) - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -67,11 +71,13 @@ class LocalSubscriptionTests: XCTestCase { return storageEngine } let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true @@ -112,14 +118,16 @@ class LocalSubscriptionTests: XCTestCase { } } - let model = Post(id: UUID().uuidString, - title: "Test Post", - content: "Test Post Content", - createdAt: .now(), - updatedAt: nil, - draft: false, - rating: nil, - comments: []) + let model = Post( + id: UUID().uuidString, + title: "Test Post", + content: "Test Post Content", + createdAt: .now(), + updatedAt: nil, + draft: false, + rating: nil, + comments: [] + ) _ = try await Amplify.DataStore.save(model) await fulfillment(of: [receivedMutationEvent], timeout: 1.0) @@ -147,14 +155,16 @@ class LocalSubscriptionTests: XCTestCase { } } - let model = Post(id: UUID().uuidString, - title: "Test Post", - content: "Test Post Content", - createdAt: .now(), - updatedAt: nil, - draft: false, - rating: nil, - comments: []) + let model = Post( + id: UUID().uuidString, + title: "Test Post", + content: "Test Post Content", + createdAt: .now(), + updatedAt: nil, + draft: false, + rating: nil, + comments: [] + ) _ = try await Amplify.DataStore.save(model) await fulfillment(of: [receivedMutationEvent], timeout: 1.0) @@ -169,14 +179,16 @@ class LocalSubscriptionTests: XCTestCase { /// - I am notified of `update` mutations func testUpdate() async throws { let originalContent = "Content as of \(Date())" - let model = Post(id: UUID().uuidString, - title: "Test Post", - content: originalContent, - createdAt: .now(), - updatedAt: nil, - draft: false, - rating: nil, - comments: []) + let model = Post( + id: UUID().uuidString, + title: "Test Post", + content: originalContent, + createdAt: .now(), + updatedAt: nil, + draft: false, + rating: nil, + comments: [] + ) _ = try await Amplify.DataStore.save(model) @@ -198,7 +210,7 @@ class LocalSubscriptionTests: XCTestCase { XCTFail("Unexpected error: \(error)") } } - + _ = try await Amplify.DataStore.save(newModel) await fulfillment(of: [receivedMutationEvent], timeout: 1.0) @@ -228,9 +240,11 @@ class LocalSubscriptionTests: XCTestCase { } } - let model = Post(title: "Test Post", - content: "Test Post Content", - createdAt: .now()) + let model = Post( + title: "Test Post", + content: "Test Post Content", + createdAt: .now() + ) _ = try await Amplify.DataStore.save(model) _ = try await Amplify.DataStore.delete(model) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift index c20ad32848..6d63939ea9 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest import Combine @testable import Amplify -@testable import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import AWSPluginsCore /// Tests behavior of local DataStore subscriptions (as opposed to remote API subscription behaviors) /// using serialized JSON models @@ -38,8 +38,10 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let outgoingMutationQueue = NoOpMutationQueue() let mutationDatabaseAdapter = try AWSMutationDatabaseAdapter(storageAdapter: storageAdapter) let awsMutationEventPublisher = AWSMutationEventPublisher(eventSource: mutationDatabaseAdapter) - stateMachine = MockStateMachine(initialState: .notStarted, - resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:)) + stateMachine = MockStateMachine( + initialState: .notStarted, + resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:) + ) let syncEngine = RemoteSyncEngine( storageAdapter: storageAdapter, @@ -55,11 +57,13 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { requestRetryablePolicy: MockRequestRetryablePolicy() ) - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -69,11 +73,13 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { return storageEngine } let dataStorePublisher = DataStorePublisher() - dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestJsonModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestJsonModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true @@ -121,9 +127,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! dataStorePlugin.save(model, modelSchema: postSchema) { _ in } @@ -160,24 +168,29 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { print("Ignore") } - }) + } + ) // insert a post let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! dataStorePlugin.save(model, modelSchema: postSchema) { _ in } // insert a comment let commentContent = "some content" - let comment = ["content": .string(commentContent), - "createdAt": .string(createdAt), - "post": .object(model.values)] as [String: JSONValue] + let comment = [ + "content": .string(commentContent), + "createdAt": .string(createdAt), + "post": .object(model.values) + ] as [String: JSONValue] let commentModel = DynamicModel(values: comment) let commentSchema = ModelRegistry.modelSchema(from: "Comment")! dataStorePlugin.save(commentModel, modelSchema: commentSchema) { result in @@ -219,9 +232,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! dataStorePlugin.save(model, modelSchema: postSchema) { _ in } @@ -239,9 +254,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let originalContent = "Content as of \(Date())" let title = "a title" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(originalContent), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(originalContent), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! @@ -305,9 +322,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! dataStorePlugin.save(model, modelSchema: postSchema) { _ in } @@ -344,9 +363,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let title = "a title" let content = "some content" let createdAt = Temporal.DateTime.now().iso8601String - let post = ["title": .string(title), - "content": .string(content), - "createdAt": .string(createdAt)] as [String: JSONValue] + let post = [ + "title": .string(title), + "content": .string(content), + "createdAt": .string(createdAt) + ] as [String: JSONValue] let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! let savedPost = expectation(description: "post saved") @@ -362,9 +383,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { wait(for: [savedPost], timeout: 1.0) let commentContent = "some content" - let comment = ["content": .string(commentContent), - "createdAt": .string(createdAt), - "post": .object(model.values)] as [String: JSONValue] + let comment = [ + "content": .string(commentContent), + "createdAt": .string(createdAt), + "post": .object(model.values) + ] as [String: JSONValue] let commentModel = DynamicModel(values: comment) let commentSchema = ModelRegistry.modelSchema(from: "Comment")! let savedComment = expectation(description: "comment saved") @@ -380,9 +403,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { wait(for: [savedComment], timeout: 1.0) let queryCommentSuccess = expectation(description: "querying for comment should exist") - dataStorePlugin.query(DynamicModel.self, - modelSchema: commentSchema, - where: DynamicModel.keys.id == commentModel.id) { result in + dataStorePlugin.query( + DynamicModel.self, + modelSchema: commentSchema, + where: DynamicModel.keys.id == commentModel.id + ) { result in switch result { case .success(let comments): XCTAssertEqual(comments.count, 1) @@ -406,9 +431,11 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { subscriptionPost.cancel() let queryCommentEmpty = expectation(description: "querying for comment should be empty") - dataStorePlugin.query(DynamicModel.self, - modelSchema: commentSchema, - where: DynamicModel.keys.id == commentModel.id) { result in + dataStorePlugin.query( + DynamicModel.self, + modelSchema: commentSchema, + where: DynamicModel.keys.id == commentModel.id + ) { result in switch result { case .success(let comments): XCTAssertEqual(comments.count, 0) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationDatabaseAdapterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationDatabaseAdapterTests.swift index ff87ba4b70..7c999ec533 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationDatabaseAdapterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationDatabaseAdapterTests.swift @@ -9,10 +9,10 @@ import Foundation import SQLite import XCTest +import AWSPluginsCore @testable import Amplify @testable import AmplifyTestCommon @testable import AWSDataStorePlugin -import AWSPluginsCore class AWSMutationDatabaseAdapterTests: XCTestCase { var databaseAdapter: AWSMutationDatabaseAdapter! @@ -30,12 +30,16 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_replaceLocal_localCreateCandidateUpdate() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -43,42 +47,54 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_saveCandidate_CanadidateUpdateWithCondition() throws { - let anyLocal = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) + let anyLocal = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) let queryPredicate = post.title == model1.title let graphQLFilterJSON = try GraphQLFilterConverter.toJSON(queryPredicate, modelSchema: model1.schema) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update, - graphQLFilterJSON: graphQLFilterJSON) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update, + graphQLFilterJSON: graphQLFilterJSON + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [anyLocal]) XCTAssertEqual(disposition, .saveCandidate) } func test_saveCandidate_CanadidateDeleteWithCondition() throws { - let anyLocal = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) + let anyLocal = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) let queryPredicate = post.title == model1.title let graphQLFilterJSON = try GraphQLFilterConverter.toJSON(queryPredicate, modelSchema: model1.schema) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete, - graphQLFilterJSON: graphQLFilterJSON) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete, + graphQLFilterJSON: graphQLFilterJSON + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [anyLocal]) XCTAssertEqual(disposition, .saveCandidate) } func test_replaceLocal_BothUpdate() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -86,12 +102,16 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_replaceLocal_localUpdateCandidateDelete() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -99,12 +119,16 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_replaceLocal_BothDelete() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -112,12 +136,16 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_dropCandidate_localCreateCandidateDelete() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -125,12 +153,16 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_dropCandidateWithError_localItemExistsAlreadyCandidateCreates() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.create) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.create + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) @@ -138,31 +170,39 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } func test_dropCandidateWithError_updateMutationForItemMarkedDeleted() throws { - let localCreate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.delete) - let candidateUpdate = try MutationEvent(model: model1, - modelSchema: model1.schema, - mutationType: MutationEvent.MutationType.update) + let localCreate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.delete + ) + let candidateUpdate = try MutationEvent( + model: model1, + modelSchema: model1.schema, + mutationType: MutationEvent.MutationType.update + ) let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate]) XCTAssertEqual(disposition, .dropCandidateWithError(DataStoreError.unknown("", "", nil))) } - + /// Retrieve the first MutationEvent func test_getNextMutationEvent_AlreadyInProcess() async { let queryExpectation = expectation(description: "query called") let getMutationEventCompleted = expectation(description: "getNextMutationEvent completed") - var mutationEvent1 = MutationEvent(modelId: "1111-22", - modelName: "Post", - json: "{}", - mutationType: .create) + var mutationEvent1 = MutationEvent( + modelId: "1111-22", + modelName: "Post", + json: "{}", + mutationType: .create + ) mutationEvent1.inProcess = true - let mutationEvent2 = MutationEvent(modelId: "1111-22", - modelName: "Post", - json: "{}", - mutationType: .create) + let mutationEvent2 = MutationEvent( + modelId: "1111-22", + modelName: "Post", + json: "{}", + mutationType: .create + ) let queryResponder = QueryModelTypePredicateResponder { _, _ in queryExpectation.fulfill() return .success([mutationEvent1, mutationEvent2]) @@ -177,23 +217,27 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } getMutationEventCompleted.fulfill() } - + await fulfillment(of: [getMutationEventCompleted, queryExpectation], timeout: 1) } - + /// Retrieve the first MutationEvent func test_getNextMutationEvent_MarkInProcess() async { let queryExpectation = expectation(description: "query called") let getMutationEventCompleted = expectation(description: "getNextMutationEvent completed") - let mutationEvent1 = MutationEvent(modelId: "1111-22", - modelName: "Post", - json: "{}", - mutationType: .create) + let mutationEvent1 = MutationEvent( + modelId: "1111-22", + modelName: "Post", + json: "{}", + mutationType: .create + ) XCTAssertFalse(mutationEvent1.inProcess) - let mutationEvent2 = MutationEvent(modelId: "1111-22", - modelName: "Post", - json: "{}", - mutationType: .create) + let mutationEvent2 = MutationEvent( + modelId: "1111-22", + modelName: "Post", + json: "{}", + mutationType: .create + ) let queryResponder = QueryModelTypePredicateResponder { _, _ in queryExpectation.fulfill() return .success([mutationEvent1, mutationEvent2]) @@ -206,10 +250,10 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { case .failure(let error): XCTFail("Should have been successful result, error: \(error)") } - + getMutationEventCompleted.fulfill() } - + await fulfillment(of: [getMutationEventCompleted, queryExpectation], timeout: 1) } @@ -226,18 +270,22 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { let oldestCreatedAt = Temporal.DateTime.now().add(value: -1, to: .second) let newerCreatedAt = Temporal.DateTime.now().add(value: 1, to: .second) databaseAdapter.storageAdapter = storageAdapter - let m1 = MutationEvent(modelId: "m1", - modelName: "Post", - json: "{}", - mutationType: .create, - createdAt: newerCreatedAt, - inProcess: false) - let m2 = MutationEvent(modelId: "m2", - modelName: "Post", - json: "{}", - mutationType: .create, - createdAt: oldestCreatedAt, - inProcess: false) + let m1 = MutationEvent( + modelId: "m1", + modelName: "Post", + json: "{}", + mutationType: .create, + createdAt: newerCreatedAt, + inProcess: false + ) + let m2 = MutationEvent( + modelId: "m2", + modelName: "Post", + json: "{}", + mutationType: .create, + createdAt: oldestCreatedAt, + inProcess: false + ) let setUpM1 = storageAdapter.save(m1, modelSchema: MutationEvent.schema) guard case .success = setUpM1 else { XCTFail("Could not set up mutation event: \(m1)") @@ -282,9 +330,11 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { await fulfillment(of: [secondQueryCompleted], timeout: 1) // (3) - storageAdapter.delete(MutationEvent.self, - modelSchema: MutationEvent.schema, - withId: m2.id) { result in + storageAdapter.delete( + MutationEvent.self, + modelSchema: MutationEvent.schema, + withId: m2.id + ) { result in switch result { case .success: break @@ -312,8 +362,10 @@ class AWSMutationDatabaseAdapterTests: XCTestCase { } extension AWSMutationDatabaseAdapter.MutationDisposition: Equatable { - public static func == (lhs: AWSMutationDatabaseAdapter.MutationDisposition, - rhs: AWSMutationDatabaseAdapter.MutationDisposition) -> Bool { + public static func == ( + lhs: AWSMutationDatabaseAdapter.MutationDisposition, + rhs: AWSMutationDatabaseAdapter.MutationDisposition + ) -> Bool { switch (lhs, rhs) { case (.dropCandidateWithError, .dropCandidateWithError): return true diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationEventIngesterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationEventIngesterTests.swift index 40dfb6a6b6..a3a9880143 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationEventIngesterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/AWSMutationEventIngesterTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -36,26 +36,32 @@ class AWSMutationEventIngesterTests: XCTestCase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - let syncEngine = try RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault()) + let syncEngine = try RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault() + ) let validAPIPluginKey = "MockAPICategoryPlugin" let validAuthPluginKey = "MockAuthCategoryPlugin" - let storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let storageEngineBehaviorFactory: StorageEngineBehaviorFactory = {_, _, _, _, _, _ throws in return storageEngine } let publisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: publisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: publisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) try Amplify.add(plugin: apiPlugin) try Amplify.add(plugin: dataStorePlugin) @@ -71,9 +77,11 @@ class AWSMutationEventIngesterTests: XCTestCase { /// - Then: /// - The mutation queue writes events func testMutationQueueWritesSaveEvents() async throws { - let post = Post(title: "Post title", - content: "Post content", - createdAt: .now()) + let post = Post( + title: "Post title", + content: "Post content", + createdAt: .now() + ) _ = try await Amplify.DataStore.save(post) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift index 56860bea60..7ab2367f33 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift @@ -10,8 +10,8 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class MutationEventClearStateTests: XCTestCase { var mockStorageAdapter: MockSQLiteStorageEngineAdapter! @@ -29,10 +29,12 @@ class MutationEventClearStateTests: XCTestCase { let queryResponder = QueryModelTypePredicateResponder { _, _ in queryExpectation.fulfill() - var mutationEvent = MutationEvent(modelId: "1111-22", - modelName: "Post", - json: "{}", - mutationType: .create) + var mutationEvent = MutationEvent( + modelId: "1111-22", + modelName: "Post", + json: "{}", + mutationType: .create + ) mutationEvent.inProcess = true return .success([mutationEvent]) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift index 780d80425b..fececa69ab 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift @@ -30,10 +30,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - I receive an error /// - The mutation queue retains the original event func test_create_create() async { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -51,8 +53,10 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -83,10 +87,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is updated with the new values func test_create_update() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -103,8 +109,10 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -122,7 +130,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { } mutationEventVerified.fulfill() } - + await fulfillment(of: [mutationEventVerified], timeout: 1.0) } @@ -133,10 +141,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The delete is saved to DataStore /// - The mutation event is removed from the mutation queue func test_create_delete() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -145,13 +155,15 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { try setUpDataStore() try await startAmplifyAndWaitForSync() } - + try await Amplify.DataStore.delete(post) let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -173,10 +185,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - I receive an error /// - The mutation queue retains the original event func test_update_create() async { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -194,15 +208,19 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) case .success(let mutationEvents): XCTAssertEqual(mutationEvents.count, 1) - XCTAssertEqual(mutationEvents.first?.mutationType, - GraphQLMutationType.update.rawValue) + XCTAssertEqual( + mutationEvents.first?.mutationType, + GraphQLMutationType.update.rawValue + ) let firstEventJSON = mutationEvents[0].json let firstEventData = Data(firstEventJSON.utf8) guard let mutationEventPost = try? JSONDecoder().decode( @@ -228,10 +246,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is updated with the new values func test_update_update() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -248,8 +268,10 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -267,7 +289,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { } mutationEventVerified.fulfill() } - + await fulfillment(of: [mutationEventVerified], timeout: 1.0) } @@ -278,10 +300,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The delete is saved to DataStore /// - The mutation event is updated to a .delete type func test_update_delete() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -290,13 +314,15 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { try setUpDataStore() try await startAmplifyAndWaitForSync() } - + try await Amplify.DataStore.delete(post) let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -322,10 +348,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - I receive an error /// - The mutation queue retains the original event func test_delete_create() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -343,8 +371,10 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -369,10 +399,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - I receive an error /// - The mutation queue retains the original event func test_delete_update() async { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -393,8 +425,10 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let mutationEventVerified = expectation(description: "Verified mutation event") let predicate = MutationEvent.keys.id == SyncEngineTestBase.mutationEventId(for: post) - storageAdapter.query(MutationEvent.self, - predicate: predicate) { result in + storageAdapter.query( + MutationEvent.self, + predicate: predicate + ) { result in switch result { case .failure(let dataStoreError): XCTAssertNil(dataStoreError) @@ -420,10 +454,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is appended to the queue func testCreateMutationAppendedToEmptyQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -433,7 +469,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let savedPost = try await Amplify.DataStore.save(post) XCTAssertNotNil(savedPost) - + let mutationEventVerified = expectation(description: "Verified mutation event") storageAdapter.query(MutationEvent.self, predicate: nil) { result in switch result { @@ -464,10 +500,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is appended to the queue func testUpdateMutationAppendedToEmptyQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -509,10 +547,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is appended to the queue func testDeleteMutationAppendedToEmptyQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -551,10 +591,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is appended to the queue, even though it would normally have thrown an error func testCreateMutationAppendedToInProcessQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -565,7 +607,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { let savedPost = try await Amplify.DataStore.save(post) XCTAssertNotNil(savedPost) - + let mutationEventVerified = expectation(description: "Verified mutation event") storageAdapter.query(MutationEvent.self, predicate: nil) { result in switch result { @@ -590,10 +632,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The mutation event is appended to the queue, even though it would normally have overwritten the existing /// create func testUpdateMutationAppendedToInProcessQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -643,10 +687,12 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { /// - The update is saved to DataStore /// - The mutation event is appended to the queue, even though it would normally have thrown an error func testDeleteMutationAppendedToInProcessQueue() async throws { - let post = Post(id: "post-1", - title: "title", - content: "content", - createdAt: .now()) + let post = Post( + id: "post-1", + title: "title", + content: "content", + createdAt: .now() + ) await tryOrFail { try setUpStorageAdapter(preCreating: [Post.self, Comment.self]) @@ -657,7 +703,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { } try await Amplify.DataStore.delete(post) - + let mutationEventVerified = expectation(description: "Verified mutation event") storageAdapter.query(MutationEvent.self, predicate: nil) { result in switch result { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift index 63f1acd748..564a89e393 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import SQLite import Combine +import SQLite +import XCTest +@_implementationOnly import AmplifyAsyncTesting @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin -@_implementationOnly import AmplifyAsyncTesting +@testable import AWSPluginsCore class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { @@ -36,13 +36,11 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { } } - let connectionError: APIError = { - APIError.networkError( - "TEST: Network not available", - nil, - URLError(.notConnectedToInternet) - ) - }() + let connectionError: APIError = .networkError( + "TEST: Network not available", + nil, + URLError(.notConnectedToInternet) + ) override func setUpWithError() throws { cancellables = [] @@ -96,8 +94,8 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { // The first response is a success for the initial "Create" mutation let apiRespondedWithSuccess = expectation(description: "apiRespondedWithSuccess") - let acceptInitialMutation = setUpInitialMutationRequestResponder( - for: try post.eraseToAnyModel(), + let acceptInitialMutation = try setUpInitialMutationRequestResponder( + for: post.eraseToAnyModel(), fulfilling: apiRespondedWithSuccess, incrementing: version ) @@ -164,7 +162,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { // the RemoteSyncEngine will stop the outgoing mutation queue. We will set the retry // advice interval to be very high, so it will be preempted by the "network available" // message we send later. - + let networkUnavailable = expectation(description: "networkUnavailable") setUpNetworkUnavailableListener( fulfillingWhenNetworkUnavailable: networkUnavailable @@ -227,13 +225,13 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { setUpOutboxEmptyListener( fulfillingWhenOutboxEmpty: outboxEmpty ) - + // Once we've rejected some mutations due to an unreachable network, we'll allow the final // mutation to succeed. This is where we will assert that we've seen the last mutation // to be processed let expectedFinalContentReceived = expectation(description: "expectedFinalContentReceived") - let acceptSubsequentMutations = setUpSubsequentMutationRequestResponder( - for: try post.eraseToAnyModel(), + let acceptSubsequentMutations = try setUpSubsequentMutationRequestResponder( + for: post.eraseToAnyModel(), fulfilling: expectedFinalContentReceived, whenContentContains: expectedFinalContent, incrementing: version @@ -247,7 +245,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { setUpNetworkAvailableListener( fulfillingWhenNetworkAvailableAgain: networkAvailableAgain ) - + apiPlugin.responders = [.mutateRequestResponse: acceptSubsequentMutations] reachabilitySubject.send(ReachabilityUpdate(isOnline: true)) @@ -297,7 +295,8 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { ) -> MutateRequestResponder> { MutateRequestResponder> { request in guard let input = request.variables?["input"] as? [String: Any], - let content = input["content"] as? String else { + let content = input["content"] as? String + else { XCTFail("Unexpected request structure: no `content` in variables.") return .failure(.unknown("Unexpected request structure: no `content` in variables.", "", nil)) } @@ -312,7 +311,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { version: version.increment() ) ) - + if content == expectedFinalContent { expectation.fulfill() } @@ -342,7 +341,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { } .store(in: &cancellables) } - + private func setUpNetworkAvailableListener( fulfillingWhenNetworkAvailableAgain networkAvailableAgain: XCTestExpectation ) { @@ -356,14 +355,14 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { XCTFail("Failed to cast payload data as NetworkStatusEvent") return } - + if networkStatusEvent.active { networkAvailableAgain.fulfill() } } .store(in: &cancellables) } - + private func setUpSyncStartedListener( fulfillingWhenSyncStarted syncStarted: XCTestExpectation ) { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift index 8802e832ff..e0a51437f5 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class OutgoingMutationQueueTests: SyncEngineTestBase { @@ -146,7 +146,7 @@ class OutgoingMutationQueueTests: SyncEngineTestBase { let mutationEventSaved = expectation(description: "Preloaded mutation event saved") mutationEventSaved.expectedFulfillmentCount = 2 - let posts = (1...2).map { Post( + let posts = (1 ... 2).map { Post( id: "pendingPost-\($0)", title: "pendingPost-\($0) title", content: "pendingPost-\($0) content", @@ -168,15 +168,16 @@ class OutgoingMutationQueueTests: SyncEngineTestBase { apiPlugin.responders[.mutateRequestResponse] = MutateRequestResponder> { request in if let variables = request.variables?["input"] as? [String: Any], let postId = variables["id"] as? String, - let post = posts.first(where: { $0.id == postId }) - { + let post = posts.first(where: { $0.id == postId }) { try? await Task.sleep(seconds: timeout + 1) let anyModel = try! post.eraseToAnyModel() - let remoteSyncMetadata = MutationSyncMetadata(modelId: post.id, - modelName: Post.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: post.id, + modelName: Post.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) return .success(remoteMutationSync) } @@ -184,7 +185,7 @@ class OutgoingMutationQueueTests: SyncEngineTestBase { } - postMutationEvents.forEach { event in + for event in postMutationEvents { storageAdapter.save(event) { result in switch result { case .failure(let dataStoreError): @@ -239,9 +240,11 @@ class OutgoingMutationQueueTests: SyncEngineTestBase { } await tryOrFail { - try setUpDataStore(mutationQueue: OutgoingMutationQueue(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy())) + try setUpDataStore(mutationQueue: OutgoingMutationQueue( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy() + )) try await startAmplify() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift index 722a3821c2..60936a7068 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class OutgoingMutationQueueMockStateTest: XCTestCase { var mutationQueue: OutgoingMutationQueue! @@ -29,13 +29,17 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { XCTFail(String(describing: "Unable to setup API category for unit tests")) } ModelRegistry.register(modelType: Post.self) - stateMachine = MockStateMachine(initialState: .notInitialized, - resolver: OutgoingMutationQueue.Resolver.resolve(currentState:action:)) + stateMachine = MockStateMachine( + initialState: .notInitialized, + resolver: OutgoingMutationQueue.Resolver.resolve(currentState:action:) + ) storageAdapter = MockSQLiteStorageEngineAdapter() - mutationQueue = OutgoingMutationQueue(stateMachine, - storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + mutationQueue = OutgoingMutationQueue( + stateMachine, + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy() + ) eventSource = MockMutationEventSource() publisher = AWSMutationEventPublisher(eventSource: eventSource) apiBehavior = MockAPICategoryPlugin() @@ -49,10 +53,12 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { expect.fulfill() } - mutationQueue = OutgoingMutationQueue(stateMachine, - storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy()) + mutationQueue = OutgoingMutationQueue( + stateMachine, + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy() + ) await fulfillment(of: [expect], timeout: 1) XCTAssertEqual(stateMachine.state, OutgoingMutationQueue.State.notInitialized) @@ -79,10 +85,12 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { await fulfillment(of: [receivedSubscription], timeout: 1.0) let json = "{\"id\":\"1234\",\"title\":\"t\",\"content\":\"c\",\"createdAt\":\"2020-09-03T22:55:13.424Z\"}" - let futureResult = MutationEvent(modelId: "1", - modelName: "Post", - json: json, - mutationType: MutationEvent.MutationType.create) + let futureResult = MutationEvent( + modelId: "1", + modelName: "Post", + json: json, + mutationType: MutationEvent.MutationType.create + ) eventSource.pushMutationEvent(futureResult: .success(futureResult)) let enqueueEvent = expectation(description: "state requestingEvent, enqueueEvent") @@ -97,11 +105,13 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { try! await Task.sleep(seconds: 0.5) let model = MockSynced(id: "id-1") let anyModel = try! model.eraseToAnyModel() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: MockSynced.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: MockSynced.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) return .success(remoteMutationSync) } @@ -143,12 +153,16 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { await fulfillment(of: [receivedSubscription], timeout: 0.1) // Mock incoming mutation event - let post = Post(title: "title", - content: "content", - createdAt: .now()) - let futureResult = try MutationEvent(model: post, - modelSchema: post.schema, - mutationType: .create) + let post = Post( + title: "title", + content: "content", + createdAt: .now() + ) + let futureResult = try MutationEvent( + model: post, + modelSchema: post.schema, + mutationType: .create + ) eventSource.pushMutationEvent(futureResult: .success(futureResult)) let enqueueEvent = expectation(description: "state requestingEvent, enqueueEvent") @@ -163,11 +177,13 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { try! await Task.sleep(seconds: 0.3) let model = MockSynced(id: "id-1") let anyModel = try! model.eraseToAnyModel() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: MockSynced.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: MockSynced.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) return .success(remoteMutationSync) } @@ -191,15 +207,19 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { // Re-enable syncing let startReceivedAgain = expectation(description: "Start received again") stateMachine.pushExpectActionCriteria { action in - XCTAssertEqual(action, OutgoingMutationQueue.Action.receivedStart(self.apiBehavior, - self.publisher, - self.reconciliationQueue)) + XCTAssertEqual(action, OutgoingMutationQueue.Action.receivedStart( + self.apiBehavior, + self.publisher, + self.reconciliationQueue + )) startReceivedAgain.fulfill() } - mutationQueue.startSyncingToCloud(api: apiBehavior, - mutationEventPublisher: publisher, - reconciliationQueue: reconciliationQueue) + mutationQueue.startSyncingToCloud( + api: apiBehavior, + mutationEventPublisher: publisher, + reconciliationQueue: reconciliationQueue + ) await fulfillment(of: [startReceivedAgain], timeout: 1) @@ -281,11 +301,13 @@ extension OutgoingMutationQueueMockStateTest { await Amplify.reset() let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: "MockAPICategoryPlugin", - validAuthPluginKey: "MockAuthCategoryPlugin") + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: "MockAPICategoryPlugin", + validAuthPluginKey: "MockAuthCategoryPlugin" + ) try Amplify.add(plugin: dataStorePlugin) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift index fc2133fa69..5adb099cdd 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore // swiftlint:disable type_body_length // swiftlint:disable type_name @@ -73,12 +73,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - apiError: apiError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + apiError: apiError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -116,12 +118,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - apiError: apiError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + apiError: apiError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -159,12 +163,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -203,12 +209,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -248,12 +256,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -299,12 +309,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectHubEvent, expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) Amplify.Hub.removeListener(hubListener) @@ -339,12 +351,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -378,12 +392,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -417,12 +433,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectErrorHandlerCalled.fulfill() }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -434,8 +452,10 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { /// - Unexpected scenario, there should never be an conflict unhandled error without error.data func testConflictUnhandledReturnsErrorForMissingRemoteModel() throws { let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .create) - let graphQLError = GraphQLError(message: "conflict unhandled", - extensions: ["errorType": .string(AppSyncErrorType.conflictUnhandled.rawValue)]) + let graphQLError = GraphQLError( + message: "conflict unhandled", + extensions: ["errorType": .string(AppSyncErrorType.conflictUnhandled.rawValue)] + ) let graphQLResponseError = GraphQLResponseError>.error([graphQLError]) let expectCompletion = expectation(description: "Expect to complete error processing") let completion: (Result) -> Void = { result in @@ -449,12 +469,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { XCTAssertEqual(dataStoreError.errorDescription, "Missing remote model from the response from AppSync.") expectCompletion.fulfill() } - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: .testDefault(), - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: .testDefault(), + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -467,9 +489,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { func testConflictUnhandledReturnsErrorForCreateMutation() throws { let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .create) let remotePost = Post(title: "remoteTitle", content: "remoteContent", createdAt: .now()) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 1) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 1 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -485,12 +509,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { XCTAssertEqual(dataStoreError.errorDescription, "Should never get conflict unhandled for create mutation") expectCompletion.fulfill() } - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: .testDefault(), - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: .testDefault(), + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -504,9 +530,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .delete) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: true, - version: 1) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: true, + version: 1 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -515,12 +543,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { self.assertSuccessfulNil(result) expectCompletion.fulfill() } - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: .testDefault(), - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: .testDefault(), + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } @@ -534,9 +564,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .delete) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 2) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 2 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -548,11 +580,13 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let apiMutateCalled = expectation(description: "API was called") mockAPIPlugin.responders[.mutateRequestResponse] = MutateRequestResponder> { request in - let updatedMetadata = MutationSyncMetadata(modelId: remotePost.id, - modelName: remotePost.modelName, - deleted: true, - lastChangedAt: 0, - version: 3) + let updatedMetadata = MutationSyncMetadata( + modelId: remotePost.id, + modelName: remotePost.modelName, + deleted: true, + lastChangedAt: 0, + version: 3 + ) guard let variables = request.variables, let input = variables["input"] as? [String: Any] @@ -566,7 +600,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { guard let mockResponse = ( try? localPost.eraseToAnyModel() - ).map({ MutationSync(model:$0 , syncMetadata: updatedMetadata) }) + ).map({ MutationSync(model: $0, syncMetadata: updatedMetadata) }) else { XCTFail("Failed to wrap to AnyModel") return .failure(.unknown("", "", nil)) @@ -587,14 +621,16 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectConflicthandlerCalled.fulfill() resolve(.retryLocal) }) - - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - reconciliationQueue: reconciliationQueue, - completion: completion) + + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + reconciliationQueue: reconciliationQueue, + completion: completion + ) queue.addOperation(operation) @@ -612,9 +648,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .delete) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 2) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 2 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -636,11 +674,13 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { XCTAssertTrue(request.document.contains("UpdatePost")) apiMutateCalled.fulfill() - let updatedMetadata = MutationSyncMetadata(modelId: remotePost.id, - modelName: remotePost.modelName, - deleted: false, - lastChangedAt: 0, - version: 3) + let updatedMetadata = MutationSyncMetadata( + modelId: remotePost.id, + modelName: remotePost.modelName, + deleted: false, + lastChangedAt: 0, + version: 3 + ) guard let mockResponse = (try? localPost.eraseToAnyModel()).map({ MutationSync(model: $0, syncMetadata: updatedMetadata) }) else { XCTFail("Failed to wrap to AnyModel") return .failure(.unknown("Failed to wrap to AnyModel", "", nil)) @@ -663,13 +703,15 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { resolve(.retry(retryModel)) }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - reconciliationQueue: reconciliationQueue, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + reconciliationQueue: reconciliationQueue, + completion: completion + ) queue.addOperation(operation) @@ -687,9 +729,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .delete) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 2) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 2 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -732,12 +776,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectHubEvent.fulfill() } } - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: .testDefault(), - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: .testDefault(), + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) await fulfillment(of: [modelSavedEvent], timeout: defaultAsyncWaitTimeout) @@ -1002,9 +1048,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .update) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 2) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 2 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -1086,9 +1134,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let localPost = Post(title: "localTitle", content: "localContent", createdAt: .now()) let remotePost = Post(id: localPost.id, title: "remoteTitle", content: "remoteContent", createdAt: .now()) let mutationEvent = try MutationEvent(model: localPost, modelSchema: localPost.schema, mutationType: .update) - guard let graphQLResponseError = try getGraphQLResponseError(withRemote: remotePost, - deleted: false, - version: 2) else { + guard let graphQLResponseError = try getGraphQLResponseError( + withRemote: remotePost, + deleted: false, + version: 2 + ) else { XCTFail("Couldn't get GraphQL response with remote post") return } @@ -1132,12 +1182,14 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { expectConflicthandlerCalled.fulfill() resolve(.retryLocal) }) - let operation = ProcessMutationErrorFromCloudOperation(dataStoreConfiguration: configuration, - mutationEvent: mutationEvent, - api: mockAPIPlugin, - storageAdapter: storageAdapter, - graphQLResponseError: graphQLResponseError, - completion: completion) + let operation = ProcessMutationErrorFromCloudOperation( + dataStoreConfiguration: configuration, + mutationEvent: mutationEvent, + api: mockAPIPlugin, + storageAdapter: storageAdapter, + graphQLResponseError: graphQLResponseError, + completion: completion + ) queue.addOperation(operation) await fulfillment(of: [ @@ -1166,10 +1218,12 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { XCTFail("Should have been successful") } - let graphQLError = try getGraphQLResponseError(withRemote: post, - deleted: false, - version: 0, - errorType: .operationDisabled) + let graphQLError = try getGraphQLResponseError( + withRemote: post, + deleted: false, + version: 0, + errorType: .operationDisabled + ) let operation = ProcessMutationErrorFromCloudOperation( dataStoreConfiguration: DataStoreConfiguration.testDefault(), @@ -1177,7 +1231,8 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { api: mockAPIPlugin, storageAdapter: storageAdapter, graphQLResponseError: graphQLError, - completion: completion) + completion: completion + ) queue.addOperation(operation) await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) @@ -1189,11 +1244,13 @@ extension ProcessMutationErrorFromCloudOperationTests { await Amplify.reset() let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: "MockAPICategoryPlugin", - validAuthPluginKey: "MockAuthCategoryPlugin") + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: "MockAPICategoryPlugin", + validAuthPluginKey: "MockAuthCategoryPlugin" + ) try Amplify.add(plugin: dataStorePlugin) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true @@ -1229,14 +1286,18 @@ extension ProcessMutationErrorFromCloudOperationTests { XCTAssertNil(mutationEventOptional) } - private func getGraphQLResponseError(withRemote post: Post = Post(title: "remoteTitle", - content: "remoteContent", - createdAt: .now()), - deleted: Bool = false, - version: Int = 1, - errorType: AppSyncErrorType? = .conflictUnhandled) + private func getGraphQLResponseError( + withRemote post: Post = Post( + title: "remoteTitle", + content: "remoteContent", + createdAt: .now() + ), + deleted: Bool = false, + version: Int = 1, + errorType: AppSyncErrorType? = .conflictUnhandled + ) throws -> GraphQLResponseError>? { - let data = Data(try post.toJSON().utf8) + let data = try Data(post.toJSON().utf8) let decoder = JSONDecoder() decoder.dateDecodingStrategy = ModelDateFormatting.decodingStrategy let remoteData = try decoder.decode(JSONValue.self, from: data) @@ -1247,10 +1308,14 @@ extension ProcessMutationErrorFromCloudOperationTests { remoteDataObject["_lastChangedAt"] = .number(123) remoteDataObject["_version"] = .number(Double(version)) remoteDataObject["__typename"] = .string(post.modelName) - if let errorType = errorType { - let graphQLError = GraphQLError(message: "error message", - extensions: ["errorType": .string(errorType.rawValue), - "data": .object(remoteDataObject)]) + if let errorType { + let graphQLError = GraphQLError( + message: "error message", + extensions: [ + "errorType": .string(errorType.rawValue), + "data": .object(remoteDataObject) + ] + ) return GraphQLResponseError>.error([graphQLError]) } else { let graphQLError = GraphQLError(message: "error message") @@ -1259,34 +1324,46 @@ extension ProcessMutationErrorFromCloudOperationTests { } private func graphQLError(_ errorType: AppSyncErrorType) -> GraphQLError { - GraphQLError(message: "message", - locations: nil, - path: nil, - extensions: ["errorType": .string(errorType.rawValue)]) + GraphQLError( + message: "message", + locations: nil, + path: nil, + extensions: ["errorType": .string(errorType.rawValue)] + ) } - - private func custom(errorHandler: DataStoreErrorHandler? = nil, - conflictHandler: (DataStoreConflictHandler)? = nil) -> DataStoreConfiguration { - if let conflictHandler = conflictHandler, let errorHandler = errorHandler { + + private func custom( + errorHandler: DataStoreErrorHandler? = nil, + conflictHandler: DataStoreConflictHandler? = nil + ) -> DataStoreConfiguration { + if let conflictHandler, let errorHandler { #if os(watchOS) - return .custom(errorHandler: errorHandler, - conflictHandler: conflictHandler, - disableSubscriptions: { false }) + return .custom( + errorHandler: errorHandler, + conflictHandler: conflictHandler, + disableSubscriptions: { false } + ) #else - return .custom(errorHandler: errorHandler, - conflictHandler: conflictHandler) + return .custom( + errorHandler: errorHandler, + conflictHandler: conflictHandler + ) #endif - } else if let errorHandler = errorHandler { + } else if let errorHandler { #if os(watchOS) - return .custom(errorHandler: errorHandler, - disableSubscriptions: { false }) + return .custom( + errorHandler: errorHandler, + disableSubscriptions: { false } + ) #else return .custom(errorHandler: errorHandler) #endif - } else if let conflictHandler = conflictHandler { + } else if let conflictHandler { #if os(watchOS) - return .custom(conflictHandler: conflictHandler, - disableSubscriptions: { false }) + return .custom( + conflictHandler: conflictHandler, + disableSubscriptions: { false } + ) #else return .custom(conflictHandler: conflictHandler) #endif diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/SyncMutationToCloudOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/SyncMutationToCloudOperationTests.swift index dbe8220e59..cad0cbd414 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/SyncMutationToCloudOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/SyncMutationToCloudOperationTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class SyncMutationToCloudOperationTests: XCTestCase { let defaultAsyncWaitTimeout = 2.0 @@ -53,11 +53,13 @@ class SyncMutationToCloudOperationTests: XCTestCase { return .failure(.unknown("", "", APIError.networkError("mock NotConnectedToInternetError", nil, urlError))) } else if numberOfTimesEntered == 1, let anyModel = try? model.eraseToAnyModel() { expectSecondCallToAPIMutate.fulfill() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 2 + ) return .success(MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata)) } else { XCTFail("This should not be called more than once") @@ -117,11 +119,13 @@ class SyncMutationToCloudOperationTests: XCTestCase { return .failure(.unknown("", "", APIError.networkError("mock NotConnectedToInternetError", nil, urlError))) } else if numberOfTimesEntered == 1, let anyModel = try? model.eraseToAnyModel() { expectSecondCallToAPIMutate.fulfill() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) return .success(remoteMutationSync) } else { @@ -205,12 +209,12 @@ class SyncMutationToCloudOperationTests: XCTestCase { operation.cancel() await fulfillment(of: [expectMutationRequestFailed], timeout: defaultAsyncWaitTimeout) } - + // MARK: - GetRetryAdviceIfRetryableTests - + func testGetRetryAdvice_NetworkError_RetryTrue() async throws { - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: AWSDefaultAuthModeStrategy(), @@ -218,15 +222,15 @@ class SyncMutationToCloudOperationTests: XCTestCase { currentAttemptNumber: 1, completion: { _ in } ) - + let error = APIError.networkError("", nil, URLError(.userAuthenticationRequired)) let advice = operation.getRetryAdviceIfRetryable(error: error) XCTAssertTrue(advice.shouldRetry) } - + func testGetRetryAdvice_HTTPStatusError401WithMultiAuth_RetryTrue() async throws { - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: MockMultiAuthModeStrategy(), @@ -234,15 +238,17 @@ class SyncMutationToCloudOperationTests: XCTestCase { currentAttemptNumber: 1, completion: { _ in } ) - let response = HTTPURLResponse(url: URL(string: "http://localhost")!, - statusCode: 401, - httpVersion: nil, - headerFields: nil)! + let response = HTTPURLResponse( + url: URL(string: "http://localhost")!, + statusCode: 401, + httpVersion: nil, + headerFields: nil + )! let error = APIError.httpStatusError(401, response) let advice = operation.getRetryAdviceIfRetryable(error: error) XCTAssertTrue(advice.shouldRetry) } - + /// Given: Model with multiple auth types. Mutation requests always fail with 401 error code /// When: Mutating model fails with 401 /// Then: DataStore will try again with each auth type and eventually fails @@ -251,15 +257,17 @@ class SyncMutationToCloudOperationTests: XCTestCase { let mutationEvent = try createMutationEvent() let authStrategy = MockMultiAuthModeStrategy() let expectedNumberOfTimesEntered = authStrategy.authTypesFor(schema: mutationEvent.schema, operation: .create).count - + let expectCalllToApiMutateNTimesAndFail = expectation(description: "Call API.mutate \(expectedNumberOfTimesEntered) times and then fail") - - let response = HTTPURLResponse(url: URL(string: "http://localhost")!, - statusCode: 401, - httpVersion: nil, - headerFields: nil)! + + let response = HTTPURLResponse( + url: URL(string: "http://localhost")!, + statusCode: 401, + httpVersion: nil, + headerFields: nil + )! let error = APIError.httpStatusError(401, response) - + let operation = await SyncMutationToCloudOperation( mutationEvent: mutationEvent, getLatestSyncMetadata: { nil }, @@ -270,29 +278,29 @@ class SyncMutationToCloudOperationTests: XCTestCase { completion: { result in if numberOfTimesEntered == expectedNumberOfTimesEntered { expectCalllToApiMutateNTimesAndFail.fulfill() - + } else { XCTFail("API.mutate was called incorrect amount of times, expected: \(expectedNumberOfTimesEntered), was : \(numberOfTimesEntered)") } } ) - + let responder = MutateRequestResponder> { request in defer { numberOfTimesEntered += 1 } return .failure(.unknown("", "", error)) } - + mockAPIPlugin.responders[.mutateRequestResponse] = responder let queue = OperationQueue() queue.addOperation(operation) - + await fulfillment(of: [expectCalllToApiMutateNTimesAndFail], timeout: defaultAsyncWaitTimeout) } - + func testGetRetryAdvice_OperationErrorAuthErrorWithMultiAuth_RetryTrue() async throws { - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: MockMultiAuthModeStrategy(), @@ -300,19 +308,19 @@ class SyncMutationToCloudOperationTests: XCTestCase { currentAttemptNumber: 1, completion: { _ in } ) - + let authError = AuthError.notAuthorized("", "", nil) let error = APIError.operationError("", "", authError) let advice = operation.getRetryAdviceIfRetryable(error: error) XCTAssertTrue(advice.shouldRetry) } - + func testGetRetryAdvice_OperationErrorAuthErrorWithSingleAuth_RetryFalse() async throws { let expectation = expectation(description: "operation completed") var numberOfTimesEntered = 0 var error: APIError? - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: AWSDefaultAuthModeStrategy(), @@ -343,10 +351,10 @@ class SyncMutationToCloudOperationTests: XCTestCase { await fulfillment(of: [expectation]) XCTAssertEqual(false, operation.getRetryAdviceIfRetryable(error: error!).shouldRetry) } - + func testGetRetryAdvice_OperationErrorAuthErrorSessionExpired_RetryTrue() async throws { - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: AWSDefaultAuthModeStrategy(), @@ -354,16 +362,16 @@ class SyncMutationToCloudOperationTests: XCTestCase { currentAttemptNumber: 1, completion: { _ in } ) - + let authError = AuthError.sessionExpired("", "", nil) let error = APIError.operationError("", "", authError) let advice = operation.getRetryAdviceIfRetryable(error: error) XCTAssertTrue(advice.shouldRetry) } - + func testGetRetryAdvice_OperationErrorAuthErrorSignedOut_RetryTrue() async throws { - let operation = await SyncMutationToCloudOperation( - mutationEvent: try createMutationEvent(), + let operation = try await SyncMutationToCloudOperation( + mutationEvent: createMutationEvent(), getLatestSyncMetadata: { nil }, api: mockAPIPlugin, authModeStrategy: AWSDefaultAuthModeStrategy(), @@ -371,34 +379,38 @@ class SyncMutationToCloudOperationTests: XCTestCase { currentAttemptNumber: 1, completion: { _ in } ) - + let authError = AuthError.signedOut("", "", nil) let error = APIError.operationError("", "", authError) let advice = operation.getRetryAdviceIfRetryable(error: error) XCTAssertTrue(advice.shouldRetry) } - + private func createMutationEvent() throws -> MutationEvent { let post1 = Post(title: "post1", content: "content1", createdAt: .now()) return try MutationEvent(model: post1, modelSchema: post1.schema, mutationType: .create) } - + } public class MockMultiAuthModeStrategy: AuthModeStrategy { public weak var authDelegate: AuthModeStrategyDelegate? - required public init() {} + public required init() {} - public func authTypesFor(schema: ModelSchema, - operation: ModelOperation) -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operation: ModelOperation + ) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: [ .designated(.amazonCognitoUserPools), .designated(.apiKey) ]) } - public func authTypesFor(schema: ModelSchema, - operations: [ModelOperation]) -> AWSAuthorizationTypeIterator { + public func authTypesFor( + schema: ModelSchema, + operations: [ModelOperation] + ) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: [ .designated(.amazonCognitoUserPools), .designated(.apiKey) @@ -411,11 +423,13 @@ extension SyncMutationToCloudOperationTests { await Amplify.reset() let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: "MockAPICategoryPlugin", - validAuthPluginKey: "MockAuthCategoryPlugin") + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: "MockAPICategoryPlugin", + validAuthPluginKey: "MockAuthCategoryPlugin" + ) try Amplify.add(plugin: dataStorePlugin) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift index 0192e13ed3..60b63cbf79 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest +@_implementationOnly import AmplifyAsyncTesting import Combine @testable import Amplify @testable import AmplifyTestCommon @testable import AWSDataStorePlugin -@_implementationOnly import AmplifyAsyncTesting /// Tests that DataStore invokes proper API methods to fulfill remote sync class RemoteSyncAPIInvocationTests: XCTestCase { @@ -40,13 +40,17 @@ class RemoteSyncAPIInvocationTests: XCTestCase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - let syncEngine = try RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault()) - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let syncEngine = try RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault() + ) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -55,11 +59,13 @@ class RemoteSyncAPIInvocationTests: XCTestCase { return storageEngine } let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let apiConfig = APICategoryConfiguration(plugins: [apiPlugin.key: true]) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [dataStorePlugin.key: true]) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift index fd2686b5ab..4fe9ec7c4f 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest import Combine @testable import Amplify @@ -46,7 +46,7 @@ class RemoteSyncEngineTests: XCTestCase { } func testErrorOnNilStorageAdapter() throws { - guard let remoteSyncEngine = remoteSyncEngine else { + guard let remoteSyncEngine else { XCTFail("Failed to initialize remoteSyncEngine") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RequestRetryablePolicyTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RequestRetryablePolicyTests.swift index bf4e51baa7..190c7861d5 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RequestRetryablePolicyTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RequestRetryablePolicyTests.swift @@ -18,9 +18,11 @@ class RequestRetryablePolicyTests: XCTestCase { } func testNoErrorNoHttpURLResponse() { - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssertFalse(retryAdvice.shouldRetry) XCTAssertEqual(retryAdvice.retryInterval, defaultTimeout) @@ -29,70 +31,90 @@ class RequestRetryablePolicyTests: XCTestCase { func testNoErrorWithHttpURLResponseWithRetryAfterInHeader() { let headerFields = ["Retry-After": "42"] let url = URL(string: "http://www.amazon.com")! - let httpURLResponse = HTTPURLResponse(url: url, - statusCode: 429, - httpVersion: "HTTP/1.1", - headerFields: headerFields)! - - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: 1) + let httpURLResponse = HTTPURLResponse( + url: url, + statusCode: 429, + httpVersion: "HTTP/1.1", + headerFields: headerFields + )! + + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertSeconds(retryAdvice.retryInterval, seconds: 42) } func testNoErrorWithHttpURLResponseWithoutRetryAfterInHeader_attempt1() { let url = URL(string: "http://www.amazon.com")! - let httpURLResponse = HTTPURLResponse(url: url, - statusCode: 429, - httpVersion: "HTTP/1.1", - headerFields: nil)! - - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: 1) + let httpURLResponse = HTTPURLResponse( + url: url, + statusCode: 429, + httpVersion: "HTTP/1.1", + headerFields: nil + )! + + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) } func testNoErrorWithHttpURLResponseWithoutRetryAfterInHeader_attempt2() { let url = URL(string: "http://www.amazon.com")! - let httpURLResponse = HTTPURLResponse(url: url, - statusCode: 429, - httpVersion: "HTTP/1.1", - headerFields: nil)! - - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: 2) + let httpURLResponse = HTTPURLResponse( + url: url, + statusCode: 429, + httpVersion: "HTTP/1.1", + headerFields: nil + )! + + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: 2 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 400, lessThan: 500) } func testNoErrorWithHttpURLResponseBeyondMaxWaitTime() { let url = URL(string: "http://www.amazon.com")! - let httpURLResponse = HTTPURLResponse(url: url, - statusCode: 429, - httpVersion: "HTTP/1.1", - headerFields: nil)! - - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: 12) + let httpURLResponse = HTTPURLResponse( + url: url, + statusCode: 429, + httpVersion: "HTTP/1.1", + headerFields: nil + )! + + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: 12 + ) XCTAssertFalse(retryAdvice.shouldRetry) XCTAssertEqual(retryAdvice.retryInterval, defaultTimeout) } func testNoErrorWithHttpURLResponseNotRetryable() { let url = URL(string: "http://www.amazon.com")! - let httpURLResponse = HTTPURLResponse(url: url, - statusCode: 204, - httpVersion: "HTTP/1.1", - headerFields: nil)! - - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nil, - httpURLResponse: httpURLResponse, - attemptNumber: 1) + let httpURLResponse = HTTPURLResponse( + url: url, + statusCode: 204, + httpVersion: "HTTP/1.1", + headerFields: nil + )! + + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nil, + httpURLResponse: httpURLResponse, + attemptNumber: 1 + ) XCTAssertFalse(retryAdvice.shouldRetry) XCTAssertEqual(retryAdvice.retryInterval, defaultTimeout) } @@ -101,9 +123,11 @@ class RequestRetryablePolicyTests: XCTestCase { let retryableErrorCode = URLError.init(.notConnectedToInternet) let attemptNumber = 1 - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: attemptNumber) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: attemptNumber + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -113,9 +137,11 @@ class RequestRetryablePolicyTests: XCTestCase { let retryableErrorCode = URLError.init(.notConnectedToInternet) let attemptNumber = 2 - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: attemptNumber) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: attemptNumber + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 400, lessThan: 500) @@ -125,9 +151,11 @@ class RequestRetryablePolicyTests: XCTestCase { let retryableErrorCode = URLError.init(.notConnectedToInternet) let attemptNumber = 3 - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: attemptNumber) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: attemptNumber + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 800, lessThan: 900) @@ -136,9 +164,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testDNSLookupFailedError() { let retryableErrorCode = URLError.init(.dnsLookupFailed) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -147,9 +177,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testCannotConnectToHostError() { let retryableErrorCode = URLError.init(.cannotConnectToHost) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -158,9 +190,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testCannotFindHostError() { let retryableErrorCode = URLError.init(.cannotFindHost) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -169,9 +203,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testTimedOutError() { let retryableErrorCode = URLError.init(.timedOut) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -180,20 +216,24 @@ class RequestRetryablePolicyTests: XCTestCase { func testCannotParseResponseError() { let retryableErrorCode = URLError.init(.cannotParseResponse) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) } - + func testNetworkConnectionLostError() { let retryableErrorCode = URLError.init(.networkConnectionLost) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -202,9 +242,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testUserAuthenticationRequiredError() { let retryableErrorCode = URLError.init(.userAuthenticationRequired) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -213,9 +255,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testHTTPTooManyRedirectsError() { let nonRetryableErrorCode = URLError.init(.httpTooManyRedirects) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: nonRetryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: nonRetryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssertFalse(retryAdvice.shouldRetry) XCTAssertEqual(retryAdvice.retryInterval, defaultTimeout) @@ -224,9 +268,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testSecureConnectionFailedError() { let retryableErrorCode = URLError.init(.secureConnectionFailed) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 1) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 1 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 200, lessThan: 300) @@ -235,9 +281,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testMaxValueRetryDelay() { let retryableErrorCode = URLError.init(.timedOut) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 31) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 31 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 214_748_364_800, lessThan: 214_748_364_900) @@ -246,9 +294,11 @@ class RequestRetryablePolicyTests: XCTestCase { func testBeyondMaxValueRetryDelay() { let retryableErrorCode = URLError.init(.timedOut) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 32) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 32 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 214_748_364_800, lessThan: 214_748_364_900) @@ -257,16 +307,18 @@ class RequestRetryablePolicyTests: XCTestCase { func testOverflowCase() { let retryableErrorCode = URLError.init(.timedOut) - let retryAdvice = retryPolicy.retryRequestAdvice(urlError: retryableErrorCode, - httpURLResponse: nil, - attemptNumber: 58) + let retryAdvice = retryPolicy.retryRequestAdvice( + urlError: retryableErrorCode, + httpURLResponse: nil, + attemptNumber: 58 + ) XCTAssert(retryAdvice.shouldRetry) assertMilliseconds(retryAdvice.retryInterval, greaterThan: 214_748_364_800, lessThan: 214_748_364_900) } func assertMilliseconds(_ retryInterval: DispatchTimeInterval?, greaterThan: Int, lessThan: Int) { - guard let retryInterval = retryInterval else { + guard let retryInterval else { XCTFail("retryInterval is nil") return } @@ -281,7 +333,7 @@ class RequestRetryablePolicyTests: XCTestCase { } func assertSeconds(_ retryInterval: DispatchTimeInterval?, seconds expectedSeconds: Int) { - guard let retryInterval = retryInterval else { + guard let retryInterval else { XCTFail("retryInterval is nil") return } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/StorageEngineSyncRequirementsTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/StorageEngineSyncRequirementsTests.swift index 917616005f..97629cb299 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/StorageEngineSyncRequirementsTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/StorageEngineSyncRequirementsTests.swift @@ -113,38 +113,58 @@ class StorageEngineSyncRequirementsTests: XCTestCase { XCTAssertFalse(StorageEngine.requiresAuthPlugin(apiPlugin, authRules: authRules, authModeStrategy: .default)) XCTAssertFalse(StorageEngine.requiresAuthPlugin(apiPlugin, authRules: authRules, authModeStrategy: .multiAuth)) } - + func testRequiresAuthPluginOIDCProvider_MultiAuthRules() { // OIDC requires an auth provider on the API, this is added below - let authRules = [AuthRule(allow: .owner, provider: .oidc), - AuthRule(allow: .private, provider: .iam)] + let authRules = [ + AuthRule(allow: .owner, provider: .oidc), + AuthRule(allow: .private, provider: .iam) + ] let apiPlugin = MockAPIAuthInformationPlugin() apiPlugin.defaultAuthTypeError = APIError.unknown("Could not get default auth type", "", nil) let oidcProvider = MockOIDCAuthProvider() apiPlugin.authProviderFactory = MockAPIAuthProviderFactory(oidcProvider: oidcProvider) - XCTAssertFalse(StorageEngine.requiresAuthPlugin(apiPlugin, - authRules: authRules, - authModeStrategy: .default), - "Should be false since OIDC is the default auth type on the API.") - XCTAssertTrue(StorageEngine.requiresAuthPlugin(apiPlugin, - authRules: authRules, - authModeStrategy: .multiAuth), - "Should be true since IAM requires auth plugin.") - } - + XCTAssertFalse( + StorageEngine.requiresAuthPlugin( + apiPlugin, + authRules: authRules, + authModeStrategy: .default + ), + "Should be false since OIDC is the default auth type on the API." + ) + XCTAssertTrue( + StorageEngine.requiresAuthPlugin( + apiPlugin, + authRules: authRules, + authModeStrategy: .multiAuth + ), + "Should be true since IAM requires auth plugin." + ) + } + func testRequiresAuthPluginUserPoolProvider_MultiAuthRules() { - let authRules = [AuthRule(allow: .owner, provider: .userPools), - AuthRule(allow: .private, provider: .iam)] + let authRules = [ + AuthRule(allow: .owner, provider: .userPools), + AuthRule(allow: .private, provider: .iam) + ] let apiPlugin = MockAPIAuthInformationPlugin() apiPlugin.authType = AWSAuthorizationType.amazonCognitoUserPools - XCTAssertTrue(StorageEngine.requiresAuthPlugin(apiPlugin, - authRules: authRules, - authModeStrategy: .default), - "Should be true since UserPool is the default auth type on the API.") - XCTAssertTrue(StorageEngine.requiresAuthPlugin(apiPlugin, - authRules: authRules, - authModeStrategy: .multiAuth), - "Should be true since both UserPool and IAM requires auth plugin.") + XCTAssertTrue( + StorageEngine.requiresAuthPlugin( + apiPlugin, + authRules: authRules, + authModeStrategy: .default + ), + "Should be true since UserPool is the default auth type on the API." + ) + XCTAssertTrue( + StorageEngine.requiresAuthPlugin( + apiPlugin, + authRules: authRules, + authModeStrategy: .multiAuth + ), + "Should be true since both UserPool and IAM requires auth plugin." + ) } func testRequiresAuthPluginFunctionProvider() { @@ -238,7 +258,7 @@ class StorageEngineSyncRequirementsTests: XCTestCase { func defaultAuthType(for apiName: String?) throws -> AWSAuthorizationType { if let error = defaultAuthTypeError { throw error - } else if let authType = authType { + } else if let authType { return authType } else { return .amazonCognitoUserPools diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift index 7969b27416..255b1221bb 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift @@ -10,8 +10,8 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class AWSIncomingEventReconciliationQueueTests: XCTestCase { var storageAdapter: MockSQLiteStorageEngineAdapter! @@ -42,7 +42,8 @@ class AWSIncomingEventReconciliationQueueTests: XCTestCase { storageAdapter: storageAdapter, syncExpressions: [], authModeStrategy: AWSDefaultAuthModeStrategy(), - modelReconciliationQueueFactory: modelReconciliationQueueFactory) + modelReconciliationQueueFactory: modelReconciliationQueueFactory + ) } // This test case attempts to hit a race condition, and may be required to execute multiple times @@ -216,7 +217,7 @@ class AWSIncomingEventReconciliationQueueTests: XCTestCase { XCTFail("Should not expect any other state, received: \(event)") } }) - + let reconciliationQueues = MockModelReconciliationQueue.mockModelReconciliationQueues for (queueName, queue) in reconciliationQueues { let cancellableOperation = CancelAwareBlockOperation { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisherTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisherTests.swift index 3adb5410c2..f9ec503fc6 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisherTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/IncomingAsyncSubscriptionEventPublisherTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore final class IncomingAsyncSubscriptionEventPublisherTests: XCTestCase { var apiPlugin: MockAPICategoryPlugin! @@ -41,7 +41,8 @@ final class IncomingAsyncSubscriptionEventPublisherTests: XCTestCase { modelPredicate: nil, auth: nil, authModeStrategy: AWSDefaultAuthModeStrategy(), - awsAuthService: nil) + awsAuthService: nil + ) let mapper = IncomingAsyncSubscriptionEventToAnyModelMapper() asyncEvents.subscribe(subscriber: mapper) let sink = mapper @@ -74,7 +75,8 @@ final class IncomingAsyncSubscriptionEventPublisherTests: XCTestCase { modelPredicate: nil, auth: nil, authModeStrategy: AWSDefaultAuthModeStrategy(), - awsAuthService: nil) + awsAuthService: nil + ) let mapper = IncomingAsyncSubscriptionEventToAnyModelMapper() asyncEvents.subscribe(subscriber: mapper) let sink = mapper @@ -92,15 +94,19 @@ final class IncomingAsyncSubscriptionEventPublisherTests: XCTestCase { } ) - for index in 0..>.InProcessListener @@ -31,11 +31,13 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { } let model = MockSynced(id: "id-1") - let localSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: MockSynced.modelName, - deleted: true, - lastChangedAt: Date().unixSeconds, - version: 2) + let localSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: MockSynced.modelName, + deleted: true, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let localMetadataSaved = expectation(description: "Local metadata saved") storageAdapter.save(localSyncMetadata) { _ in localMetadataSaved.fulfill() } await fulfillment(of: [localMetadataSaved], timeout: 1) @@ -67,11 +69,13 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { } let anyModel = try model.eraseToAnyModel() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: MockSynced.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: MockSynced.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) asyncSequence.send(.data(.success(remoteMutationSync))) @@ -79,8 +83,10 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { // we have to brute-force this wait try await Task.sleep(seconds: 1.0) - let finalLocalMetadata = try storageAdapter.queryMutationSyncMetadata(for: model.id, - modelName: MockSynced.modelName) + let finalLocalMetadata = try storageAdapter.queryMutationSyncMetadata( + for: model.id, + modelName: MockSynced.modelName + ) XCTAssertEqual(finalLocalMetadata?.version, 2) XCTAssertEqual(finalLocalMetadata?.deleted, true) @@ -97,8 +103,9 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { func mockRemoteSyncEngineFor_testUpdateAfterDelete() { remoteSyncEngineSink = syncEngine .publisher - .sink(receiveCompletion: {_ in }, - receiveValue: { (event: RemoteSyncEngineEvent) in + .sink( + receiveCompletion: {_ in }, + receiveValue: { (event: RemoteSyncEngineEvent) in switch event { case .mutationsPaused: // Assume AWSIncomingEventReconciliationQueue succeeds in establishing connections @@ -120,7 +127,8 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { default: break } - }) + } + ) } /// - Given: @@ -155,7 +163,7 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { mockRemoteSyncEngineFor_testDeleteWithNoLocalModel() try await startAmplifyAndWaitForSync() } - + await fulfillment(of: [expectationListener], timeout: 1) guard let asyncSequence else { XCTFail("Incoming responder didn't set up listener") @@ -163,8 +171,10 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { } let syncReceivedNotification = expectation(description: "Received 'syncReceived' update from Hub") - let syncReceivedToken = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { _ in + let syncReceivedToken = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { _ in syncReceivedNotification.fulfill() } guard try await HubListenerTestUtilities.waitForListener(with: syncReceivedToken, timeout: 5.0) else { @@ -174,17 +184,21 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { let model = MockSynced(id: "id-1") let anyModel = try model.eraseToAnyModel() - let remoteSyncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: MockSynced.modelName, - deleted: true, - lastChangedAt: Date().unixSeconds, - version: 2) + let remoteSyncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: MockSynced.modelName, + deleted: true, + lastChangedAt: Date().unixSeconds, + version: 2 + ) let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) asyncSequence.send(.data(.success(remoteMutationSync))) await fulfillment(of: [syncReceivedNotification], timeout: 1) - let finalLocalMetadata = try storageAdapter.queryMutationSyncMetadata(for: model.id, - modelName: MockSynced.modelName) + let finalLocalMetadata = try storageAdapter.queryMutationSyncMetadata( + for: model.id, + modelName: MockSynced.modelName + ) XCTAssertEqual(finalLocalMetadata?.version, 2) XCTAssertEqual(finalLocalMetadata?.deleted, true) @@ -203,8 +217,9 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { func mockRemoteSyncEngineFor_testDeleteWithNoLocalModel() { remoteSyncEngineSink = syncEngine .publisher - .sink(receiveCompletion: {_ in }, - receiveValue: { (event: RemoteSyncEngineEvent) in + .sink( + receiveCompletion: {_ in }, + receiveValue: { (event: RemoteSyncEngineEvent) in switch event { case .mutationsPaused: // Assume AWSIncomingEventReconciliationQueue succeeds in establishing connections @@ -242,6 +257,7 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { default: break } - }) + } + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift index 34e381fba5..53e6ac0c3a 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Combine +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -27,14 +27,16 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { eventsNotSaved.fulfill() } - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) // We know this won't be nil, but we need to keep a reference to the queue in memory for the duration of the // test, and since we don't act on it otherwise, Swift warns about queue never being used. @@ -42,11 +44,13 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { for iteration in 1 ... 3 { let model = try MockSynced(id: "id-\(iteration)").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) } @@ -78,22 +82,26 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { completion(.success(model)) } - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) for iteration in 1 ... 3 { let model = try MockSynced(id: "id-\(iteration)").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) } @@ -159,22 +167,26 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { let syncExpression = DataStoreSyncExpression.syncExpression(MockSynced.schema, where: { MockSynced.keys.id == "id-1" || MockSynced.keys.id == "id-3" }) - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: syncExpression.modelPredicate(), - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: syncExpression.modelPredicate(), + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) for iteration in 1 ... 3 { let model = try MockSynced(id: "id-\(iteration)").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) } @@ -259,21 +271,25 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { completion(.success(mutationSyncMetadata)) } - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) for iteration in 1 ... 3 { let model = try MockSynced(id: "id-\(iteration)").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) } @@ -339,21 +355,25 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { completion(.success(mutationSyncMetadata)) } - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) for iteration in 1 ... 2 { let model = try MockSynced(id: "id-\(iteration)").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) } @@ -419,11 +439,13 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { }) let model = try MockSynced(id: "id-3").eraseToAnyModel() - let syncMetadata = MutationSyncMetadata(modelId: model.id, - modelName: model.modelName, - deleted: false, - lastChangedAt: Date().unixSeconds, - version: 1) + let syncMetadata = MutationSyncMetadata( + modelId: model.id, + modelName: model.modelName, + deleted: false, + lastChangedAt: Date().unixSeconds, + version: 1 + ) let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) @@ -444,11 +466,14 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { extension ModelReconciliationQueueBehaviorTests { private func completionSignalWithAppSyncError(_ error: AppSyncErrorType) -> Subscribers.Completion { let appSyncJSONValue: JSONValue = .string(error.rawValue) - let graphqlError = GraphQLError.init(message: "", - locations: nil, - path: nil, - extensions: [ - "errorType": appSyncJSONValue]) + let graphqlError = GraphQLError.init( + message: "", + locations: nil, + path: nil, + extensions: [ + "errorType": appSyncJSONValue + ] + ) let graphqlResponseError = GraphQLResponseError>.error([graphqlError]) let apiError = APIError.operationError("error message", "recovery message", graphqlResponseError) let dataStoreError = DataStoreError.api(apiError, nil) @@ -457,14 +482,16 @@ extension ModelReconciliationQueueBehaviorTests { func testProcessingUnauthorizedError() async { let eventSentViaPublisher = expectation(description: "Sent via publisher") - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) let completion = completionSignalWithAppSyncError(AppSyncErrorType.unauthorized) let queueSink = queue.publisher.sink(receiveCompletion: { value in @@ -485,14 +512,16 @@ extension ModelReconciliationQueueBehaviorTests { func testProcessingOperationDisabledError() async { let eventSentViaPublisher = expectation(description: "Sent via publisher") - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) let completion = completionSignalWithAppSyncError(AppSyncErrorType.operationDisabled) let queueSink = queue.publisher.sink(receiveCompletion: { value in @@ -513,14 +542,16 @@ extension ModelReconciliationQueueBehaviorTests { func testProcessingUnhandledErrors() async { let eventSentViaPublisher = expectation(description: "Sent via publisher") - let queue = await AWSModelReconciliationQueue(modelSchema: MockSynced.schema, - storageAdapter: storageAdapter, - api: apiPlugin, - reconcileAndSaveQueue: reconcileAndSaveQueue, - modelPredicate: modelPredicate, - auth: authPlugin, - authModeStrategy: AWSDefaultAuthModeStrategy(), - incomingSubscriptionEvents: subscriptionEventsPublisher) + let queue = await AWSModelReconciliationQueue( + modelSchema: MockSynced.schema, + storageAdapter: storageAdapter, + api: apiPlugin, + reconcileAndSaveQueue: reconcileAndSaveQueue, + modelPredicate: modelPredicate, + auth: authPlugin, + authModeStrategy: AWSDefaultAuthModeStrategy(), + incomingSubscriptionEvents: subscriptionEventsPublisher + ) let completion = completionSignalWithAppSyncError(AppSyncErrorType.conflictUnhandled) let queueSink = queue.publisher.sink(receiveCompletion: { _ in diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndLocalSaveOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndLocalSaveOperationTests.swift index 0b83465e7e..152232ed8f 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndLocalSaveOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndLocalSaveOperationTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import Foundation import XCTest -import Combine @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -36,36 +36,46 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) - anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: testPost.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: testPost.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) let testDelete = Post(id: "2", title: "post2", content: "content2", createdAt: .now()) let anyPostDelete = AnyModel(testDelete) - let anyPostDeleteMetadata = MutationSyncMetadata(modelId: "2", - modelName: testPost.modelName, - deleted: true, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 2) + let anyPostDeleteMetadata = MutationSyncMetadata( + modelId: "2", + modelName: testPost.modelName, + deleted: true, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 2 + ) anyPostDeletedMutationSync = MutationSync(model: anyPostDelete, syncMetadata: anyPostDeleteMetadata) - anyPostMutationEvent = MutationEvent(id: "1", - modelId: "3", - modelName: testPost.modelName, - json: "", - mutationType: .create) + anyPostMutationEvent = MutationEvent( + id: "1", + modelId: "3", + modelName: testPost.modelName, + json: "", + mutationType: .create + ) storageAdapter = MockSQLiteStorageEngineAdapter() storageAdapter.returnOnQuery(dataStoreResult: .none) storageAdapter.returnOnSave(dataStoreResult: .none) - stateMachine = MockStateMachine(initialState: .waiting, - resolver: ReconcileAndLocalSaveOperation.Resolver.resolve(currentState:action:)) + stateMachine = MockStateMachine( + initialState: .waiting, + resolver: ReconcileAndLocalSaveOperation.Resolver.resolve(currentState:action:) + ) - operation = ReconcileAndLocalSaveOperation(modelSchema: anyPostMutationSync.model.schema, - remoteModels: [anyPostMutationSync], - storageAdapter: storageAdapter, - stateMachine: stateMachine) + operation = ReconcileAndLocalSaveOperation( + modelSchema: anyPostMutationSync.model.schema, + remoteModels: [anyPostMutationSync], + storageAdapter: storageAdapter, + stateMachine: stateMachine + ) cancellables = Set() } @@ -103,8 +113,10 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { }.store(in: &cancellables) stateMachine.pushExpectActionCriteria { action in - XCTAssertEqual(action, - ReconcileAndLocalSaveOperation.Action.errored(DataStoreError.nilStorageAdapter())) + XCTAssertEqual( + action, + ReconcileAndLocalSaveOperation.Action.errored(DataStoreError.nilStorageAdapter()) + ) expect.fulfill() } @@ -332,34 +344,42 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { XCTAssertEqual(remoteModelToApply.remoteModel.model.id, anyPostMutationSync.model.id) } - func testSeparateDispositions_notifyDropped () async { + func testSeparateDispositions_notifyDropped() async { let expect = expectation(description: "notify dropped twice") expect.expectedFulfillmentCount = 2 let model1 = AnyModel(Post(title: "post1", content: "content", createdAt: .now())) let model2 = AnyModel(Post(title: "post2", content: "content", createdAt: .now())) - let metadata1 = MutationSyncMetadata(modelId: model1.id, - modelName: model1.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) - let metadata2 = MutationSyncMetadata(modelId: model2.id, - modelName: model2.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let metadata1 = MutationSyncMetadata( + modelId: model1.id, + modelName: model1.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) + let metadata2 = MutationSyncMetadata( + modelId: model2.id, + modelName: model2.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let remoteModel1 = MutationSync(model: model1, syncMetadata: metadata1) let remoteModel2 = MutationSync(model: model2, syncMetadata: metadata2) - let mutationEvent1 = MutationEvent(id: "1", - modelId: remoteModel1.model.id, - modelName: remoteModel1.model.modelName, - json: "", - mutationType: .create) - let mutationEvent2 = MutationEvent(id: "2", - modelId: remoteModel2.model.id, - modelName: remoteModel2.model.modelName, - json: "", - mutationType: .create) + let mutationEvent1 = MutationEvent( + id: "1", + modelId: remoteModel1.model.id, + modelName: remoteModel1.model.modelName, + json: "", + mutationType: .create + ) + let mutationEvent2 = MutationEvent( + id: "2", + modelId: remoteModel2.model.id, + modelName: remoteModel2.model.modelName, + json: "", + mutationType: .create + ) operation.publisher .sink { completion in switch completion { @@ -494,29 +514,37 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { expect.expectedFulfillmentCount = 2 let model1 = AnyModel(Post(title: "post1", content: "content", createdAt: .now())) let model2 = AnyModel(Post(title: "post2", content: "content", createdAt: .now())) - let metadata1 = MutationSyncMetadata(modelId: model1.id, - modelName: model1.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) - let metadata2 = MutationSyncMetadata(modelId: model2.id, - modelName: model2.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + let metadata1 = MutationSyncMetadata( + modelId: model1.id, + modelName: model1.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) + let metadata2 = MutationSyncMetadata( + modelId: model2.id, + modelName: model2.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) let remoteModel1 = MutationSync(model: model1, syncMetadata: metadata1) let remoteModel2 = MutationSync(model: model2, syncMetadata: metadata2) - let localMetadata1 = MutationSyncMetadata(modelId: model1.id, - modelName: model1.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 3) - let localMetadata2 = MutationSyncMetadata(modelId: model2.id, - modelName: model2.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 4) + let localMetadata1 = MutationSyncMetadata( + modelId: model1.id, + modelName: model1.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 3 + ) + let localMetadata2 = MutationSyncMetadata( + modelId: model2.id, + modelName: model2.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 4 + ) operation.publisher .sink { completion in switch completion { @@ -536,8 +564,10 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { } }.store(in: &cancellables) - let result = operation.getDispositions(for: [remoteModel1, remoteModel2], - localMetadatas: [localMetadata1, localMetadata2]) + let result = operation.getDispositions( + for: [remoteModel1, remoteModel2], + localMetadatas: [localMetadata1, localMetadata2] + ) XCTAssertTrue(result.isEmpty) await fulfillment(of: [expect], timeout: 1) @@ -854,15 +884,17 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { } func testApplyRemoteModels_skipFailedOperations() async throws { - let dispositions: [RemoteSyncReconciler.Disposition] = [.create(anyPostMutationSync), - .create(anyPostMutationSync), - .update(anyPostMutationSync), - .update(anyPostMutationSync), - .delete(anyPostMutationSync), - .delete(anyPostMutationSync), - .create(anyPostMutationSync), - .update(anyPostMutationSync), - .delete(anyPostMutationSync)] + let dispositions: [RemoteSyncReconciler.Disposition] = [ + .create(anyPostMutationSync), + .create(anyPostMutationSync), + .update(anyPostMutationSync), + .update(anyPostMutationSync), + .delete(anyPostMutationSync), + .delete(anyPostMutationSync), + .create(anyPostMutationSync), + .update(anyPostMutationSync), + .delete(anyPostMutationSync) + ] let expect = expectation(description: "should complete") let expectedDeleteSuccess = expectation(description: "delete should be successful") expectedDeleteSuccess.expectedFulfillmentCount = 3 // 3 delete depositions @@ -916,15 +948,17 @@ class ReconcileAndLocalSaveOperationTests: XCTestCase { func testApplyRemoteModels_failWithConstraintViolationShouldBeSuccessful() async { let expect = expectation(description: "should complete successfully") expect.expectedFulfillmentCount = 2 - let dispositions: [RemoteSyncReconciler.Disposition] = [.create(anyPostMutationSync), - .create(anyPostMutationSync), - .update(anyPostMutationSync), - .update(anyPostMutationSync), - .delete(anyPostMutationSync), - .delete(anyPostMutationSync), - .create(anyPostMutationSync), - .update(anyPostMutationSync), - .delete(anyPostMutationSync)] + let dispositions: [RemoteSyncReconciler.Disposition] = [ + .create(anyPostMutationSync), + .create(anyPostMutationSync), + .update(anyPostMutationSync), + .update(anyPostMutationSync), + .delete(anyPostMutationSync), + .delete(anyPostMutationSync), + .create(anyPostMutationSync), + .update(anyPostMutationSync), + .delete(anyPostMutationSync) + ] let expectDropped = expectation(description: "should notify dropped") expectDropped.expectedFulfillmentCount = dispositions.count let dataStoreError = DataStoreError.internalOperation("Failed to save", "") @@ -1087,11 +1121,13 @@ extension ReconcileAndLocalSaveOperationTests { await Amplify.reset() let dataStorePublisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: "MockAPICategoryPlugin", - validAuthPluginKey: "MockAuthCategoryPlugin") + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: MockStorageEngineBehavior.mockStorageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: "MockAPICategoryPlugin", + validAuthPluginKey: "MockAuthCategoryPlugin" + ) try Amplify.add(plugin: dataStorePlugin) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift index da06a88397..02783c8ce0 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift @@ -8,8 +8,8 @@ import XCTest @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class ReconcileAndSaveQueueTests: XCTestCase { var storageAdapter: MockSQLiteStorageEngineAdapter! @@ -20,18 +20,22 @@ class ReconcileAndSaveQueueTests: XCTestCase { ModelRegistry.register(modelType: Post.self) let testPost = Post(id: "1", title: "post1", content: "content", createdAt: .now()) let anyPost = AnyModel(testPost) - anyPostMetadata = MutationSyncMetadata(modelId: "1", - modelName: testPost.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: 1) + anyPostMetadata = MutationSyncMetadata( + modelId: "1", + modelName: testPost.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: 1 + ) anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) anyPostMutationSync = MutationSync(model: anyPost, syncMetadata: anyPostMetadata) storageAdapter = MockSQLiteStorageEngineAdapter() storageAdapter.returnOnQuery(dataStoreResult: .none) storageAdapter.returnOnSave(dataStoreResult: .none) - stateMachine = MockStateMachine(initialState: .waiting, - resolver: ReconcileAndLocalSaveOperation.Resolver.resolve(currentState:action:)) + stateMachine = MockStateMachine( + initialState: .waiting, + resolver: ReconcileAndLocalSaveOperation.Resolver.resolve(currentState:action:) + ) } func testAddOperation() throws { @@ -50,10 +54,12 @@ class ReconcileAndSaveQueueTests: XCTestCase { return } } - let operation = ReconcileAndLocalSaveOperation(modelSchema: anyPostMutationSync.model.schema, - remoteModels: [anyPostMutationSync], - storageAdapter: storageAdapter, - stateMachine: stateMachine) + let operation = ReconcileAndLocalSaveOperation( + modelSchema: anyPostMutationSync.model.schema, + remoteModels: [anyPostMutationSync], + storageAdapter: storageAdapter, + stateMachine: stateMachine + ) queue.addOperation(operation, modelName: Post.modelName) XCTAssertEqual(stateMachine.state, ReconcileAndLocalSaveOperation.State.waiting) wait(for: [operationAdded], timeout: 1) @@ -79,10 +85,12 @@ class ReconcileAndSaveQueueTests: XCTestCase { return } } - let operation = ReconcileAndLocalSaveOperation(modelSchema: anyPostMutationSync.model.schema, - remoteModels: [anyPostMutationSync], - storageAdapter: storageAdapter, - stateMachine: stateMachine) + let operation = ReconcileAndLocalSaveOperation( + modelSchema: anyPostMutationSync.model.schema, + remoteModels: [anyPostMutationSync], + storageAdapter: storageAdapter, + stateMachine: stateMachine + ) queue.addOperation(operation, modelName: Post.modelName) XCTAssertEqual(stateMachine.state, ReconcileAndLocalSaveOperation.State.waiting) wait(for: [operationAdded], timeout: 1) @@ -109,10 +117,12 @@ class ReconcileAndSaveQueueTests: XCTestCase { return } } - let operation = ReconcileAndLocalSaveOperation(modelSchema: anyPostMutationSync.model.schema, - remoteModels: [anyPostMutationSync], - storageAdapter: storageAdapter, - stateMachine: stateMachine) + let operation = ReconcileAndLocalSaveOperation( + modelSchema: anyPostMutationSync.model.schema, + remoteModels: [anyPostMutationSync], + storageAdapter: storageAdapter, + stateMachine: stateMachine + ) queue.addOperation(operation, modelName: Post.modelName) XCTAssertEqual(stateMachine.state, ReconcileAndLocalSaveOperation.State.waiting) wait(for: [operationAdded], timeout: 1) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/RemoteSyncReconcilerTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/RemoteSyncReconcilerTests.swift index 3cac3f153d..51a16369de 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/RemoteSyncReconcilerTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/RemoteSyncReconcilerTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import SQLite +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -26,8 +26,10 @@ class RemoteSyncReconcilerTests: XCTestCase { func testReconcileLocalMetadata_nilLocalMetadata() { let remoteModel = makeRemoteModel(deleted: false, version: 1) - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: nil) + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: nil + ) XCTAssertEqual(disposition, .create(remoteModel)) } @@ -35,60 +37,78 @@ class RemoteSyncReconcilerTests: XCTestCase { func testReconcileLocalMetadata_nilLocalMetadata_deletedModel() { let remoteModel = makeRemoteModel(deleted: true, version: 2) - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: nil) + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: nil + ) XCTAssertNil(disposition) } func testReconcileLocalMetadata_withLocalEqualVersion() { let remoteModel = makeRemoteModel(deleted: false, version: 1) - let localSyncMetadata = makeMutationSyncMetadata(modelId: remoteModel.model.id, - modelName: remoteModel.model.modelName, - deleted: false, - version: 1) - - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: localSyncMetadata) + let localSyncMetadata = makeMutationSyncMetadata( + modelId: remoteModel.model.id, + modelName: remoteModel.model.modelName, + deleted: false, + version: 1 + ) + + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: localSyncMetadata + ) XCTAssertEqual(disposition, nil) } func testReconcileLocalMetadata_withLocalLowerVersion() { let remoteModel = makeRemoteModel(deleted: false, version: 2) - let localSyncMetadata = makeMutationSyncMetadata(modelId: remoteModel.model.id, - modelName: remoteModel.model.modelName, - deleted: false, - version: 1) - - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: localSyncMetadata) + let localSyncMetadata = makeMutationSyncMetadata( + modelId: remoteModel.model.id, + modelName: remoteModel.model.modelName, + deleted: false, + version: 1 + ) + + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: localSyncMetadata + ) XCTAssertEqual(disposition, .update(remoteModel)) } func testReconcileLocalMetadata_withLocalLowerVersion_deletedModel() { let remoteModel = makeRemoteModel(deleted: true, version: 2) - let localSyncMetadata = makeMutationSyncMetadata(modelId: remoteModel.model.id, - modelName: remoteModel.model.modelName, - deleted: false, - version: 1) - - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: localSyncMetadata) + let localSyncMetadata = makeMutationSyncMetadata( + modelId: remoteModel.model.id, + modelName: remoteModel.model.modelName, + deleted: false, + version: 1 + ) + + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: localSyncMetadata + ) XCTAssertEqual(disposition, .delete(remoteModel)) } func testReconcileLocalMetadata_withLocalHigherVersion() { let remoteModel = makeRemoteModel(deleted: false, version: 1) - let localSyncMetadata = makeMutationSyncMetadata(modelId: remoteModel.model.id, - modelName: remoteModel.model.modelName, - deleted: false, - version: 2) - - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: localSyncMetadata) + let localSyncMetadata = makeMutationSyncMetadata( + modelId: remoteModel.model.id, + modelName: remoteModel.model.modelName, + deleted: false, + version: 2 + ) + + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: localSyncMetadata + ) XCTAssertNil(disposition) } @@ -97,13 +117,17 @@ class RemoteSyncReconcilerTests: XCTestCase { // conflict updating a deleted record, or the client is incorrectly manipulating the version func testReconcileLocalMetadata_withLocalHigherVersion_deletedModel() { let remoteModel = makeRemoteModel(deleted: true, version: 1) - let localSyncMetadata = makeMutationSyncMetadata(modelId: remoteModel.model.id, - modelName: remoteModel.model.modelName, - deleted: false, - version: 2) - - let disposition = RemoteSyncReconciler.getDisposition(remoteModel, - localMetadata: localSyncMetadata) + let localSyncMetadata = makeMutationSyncMetadata( + modelId: remoteModel.model.id, + modelName: remoteModel.model.modelName, + deleted: false, + version: 2 + ) + + let disposition = RemoteSyncReconciler.getDisposition( + remoteModel, + localMetadata: localSyncMetadata + ) XCTAssertNil(disposition) } @@ -143,22 +167,28 @@ class RemoteSyncReconcilerTests: XCTestCase { // with local metadata, not deleted remote, should be update let updateModel = makeRemoteModel(deleted: false, version: 2) - let localUpdateMetadata = makeMutationSyncMetadata(modelId: updateModel.model.id, - modelName: updateModel.model.modelName, - deleted: false, - version: 1) + let localUpdateMetadata = makeMutationSyncMetadata( + modelId: updateModel.model.id, + modelName: updateModel.model.modelName, + deleted: false, + version: 1 + ) // with local metadata, deleted remote, should be delete let deleteModel = makeRemoteModel(deleted: true, version: 2) - let localDeleteMetadata = makeMutationSyncMetadata(modelId: deleteModel.model.id, - modelName: deleteModel.model.modelName, - deleted: false, - version: 1) + let localDeleteMetadata = makeMutationSyncMetadata( + modelId: deleteModel.model.id, + modelName: deleteModel.model.modelName, + deleted: false, + version: 1 + ) let remoteModels = [createModel, droppedModel, updateModel, deleteModel] let localMetadatas = [localUpdateMetadata, localDeleteMetadata] - let dispositions = RemoteSyncReconciler.getDispositions(remoteModels, - localMetadatas: localMetadatas) + let dispositions = RemoteSyncReconciler.getDispositions( + remoteModels, + localMetadatas: localMetadatas + ) XCTAssertEqual(dispositions.count, 3) let create = expectation(description: "exactly one create") @@ -179,10 +209,10 @@ class RemoteSyncReconcilerTests: XCTestCase { } await fulfillment(of: [create, update, delete], timeout: 1) } - + func testGetDispositions_emptyLocal_singleModelAddedAndDeleted() { let sameId = UUID().uuidString - + let remoteModels = [ makeRemoteModel(modelId: sameId, deleted: false, version: 1), makeRemoteModel(modelId: sameId, deleted: true, version: 2) @@ -192,10 +222,10 @@ class RemoteSyncReconcilerTests: XCTestCase { XCTAssertTrue(dispositions.isEmpty) } - + func testGetDispositions_emptyLocal_oneModelAdded_SecondModelAddedAndDeleted() { let sameId = UUID().uuidString - + let remoteModels = [ makeRemoteModel(deleted: false, version: 1), makeRemoteModel(modelId: sameId, deleted: false, version: 1), @@ -209,44 +239,56 @@ class RemoteSyncReconcilerTests: XCTestCase { // MARK: - Utilities - private func makeMutationSyncMetadata(modelId: String, - modelName: String, - deleted: Bool = false, - version: Int = 1) -> MutationSyncMetadata { - - let remoteSyncMetadata = MutationSyncMetadata(modelId: modelId, - modelName: modelName, - deleted: deleted, - lastChangedAt: Date().unixSeconds, - version: version) + private func makeMutationSyncMetadata( + modelId: String, + modelName: String, + deleted: Bool = false, + version: Int = 1 + ) -> MutationSyncMetadata { + + let remoteSyncMetadata = MutationSyncMetadata( + modelId: modelId, + modelName: modelName, + deleted: deleted, + lastChangedAt: Date().unixSeconds, + version: version + ) return remoteSyncMetadata } - private func makeRemoteModel(modelId: String = UUID().uuidString, - deleted: Bool = false, - version: Int = 1) -> ReconcileAndLocalSaveOperation.RemoteModel { + private func makeRemoteModel( + modelId: String = UUID().uuidString, + deleted: Bool = false, + version: Int = 1 + ) -> ReconcileAndLocalSaveOperation.RemoteModel { do { let remoteMockSynced = try MockSynced(id: modelId).eraseToAnyModel() - let remoteSyncMetadata = makeMutationSyncMetadata(modelId: remoteMockSynced.id, - modelName: remoteMockSynced.modelName, - deleted: deleted, - version: version) - return ReconcileAndLocalSaveOperation.RemoteModel(model: remoteMockSynced, - syncMetadata: remoteSyncMetadata) + let remoteSyncMetadata = makeMutationSyncMetadata( + modelId: remoteMockSynced.id, + modelName: remoteMockSynced.modelName, + deleted: deleted, + version: version + ) + return ReconcileAndLocalSaveOperation.RemoteModel( + model: remoteMockSynced, + syncMetadata: remoteSyncMetadata + ) } catch { fatalError("Failed to create remote model") } } private func makeMutationEvent(modelId: String = UUID().uuidString) -> MutationEvent { - return MutationEvent(id: "mutation-1", - modelId: modelId, - modelName: MockSynced.modelName, - json: "{}", - mutationType: .create, - createdAt: .now(), - version: 1, - inProcess: false) + return MutationEvent( + id: "mutation-1", + modelId: modelId, + modelName: MockSynced.modelName, + json: "{}", + mutationType: .create, + createdAt: .now(), + version: 1, + inProcess: false + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/EquatableExtensions.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/EquatableExtensions.swift index d182dd5903..92190989c6 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/EquatableExtensions.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/EquatableExtensions.swift @@ -10,8 +10,10 @@ import AWSPluginsCore @testable import AWSDataStorePlugin extension RemoteSyncReconciler.Disposition: Equatable { - public static func == (lhs: RemoteSyncReconciler.Disposition, - rhs: RemoteSyncReconciler.Disposition) -> Bool { + public static func == ( + lhs: RemoteSyncReconciler.Disposition, + rhs: RemoteSyncReconciler.Disposition + ) -> Bool { switch (lhs, rhs) { case (.create(let model1), .create(let model2)): return model1.model.id == model2.model.id && @@ -29,8 +31,10 @@ extension RemoteSyncReconciler.Disposition: Equatable { } extension ReconcileAndLocalSaveOperation.Action: Equatable { - public static func == (lhs: ReconcileAndLocalSaveOperation.Action, - rhs: ReconcileAndLocalSaveOperation.Action) -> Bool { + public static func == ( + lhs: ReconcileAndLocalSaveOperation.Action, + rhs: ReconcileAndLocalSaveOperation.Action + ) -> Bool { switch (lhs, rhs) { case (.started(let models1), .started(let models2)): return models1.count == models2.count @@ -47,8 +51,10 @@ extension ReconcileAndLocalSaveOperation.Action: Equatable { } extension ReconcileAndLocalSaveOperation.State: Equatable { - public static func == (lhs: ReconcileAndLocalSaveOperation.State, - rhs: ReconcileAndLocalSaveOperation.State) -> Bool { + public static func == ( + lhs: ReconcileAndLocalSaveOperation.State, + rhs: ReconcileAndLocalSaveOperation.State + ) -> Bool { switch (lhs, rhs) { case (.waiting, .waiting): return true diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockModelReconciliationQueue.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockModelReconciliationQueue.swift index 251a13daf1..fc7b0924c7 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockModelReconciliationQueue.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockModelReconciliationQueue.swift @@ -5,13 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore + class MockModelReconciliationQueue: ModelReconciliationQueue { public static var mockModelReconciliationQueues: [String: MockModelReconciliationQueue] = [:] @@ -22,14 +23,16 @@ class MockModelReconciliationQueue: ModelReconciliationQueue { return modelReconciliationQueueSubject.eraseToAnyPublisher() } - init(modelSchema: ModelSchema, - storageAdapter: StorageEngineAdapter?, - api: APICategoryGraphQLBehavior, - reconcileAndSaveQueue: ReconcileAndSaveOperationQueue, - modelPredicate: QueryPredicate?, - auth: AuthCategoryBehavior?, - authModeStrategy: AuthModeStrategy, - incomingSubscriptionEvents: IncomingSubscriptionEventPublisher? = nil) { + init( + modelSchema: ModelSchema, + storageAdapter: StorageEngineAdapter?, + api: APICategoryGraphQLBehavior, + reconcileAndSaveQueue: ReconcileAndSaveOperationQueue, + modelPredicate: QueryPredicate?, + auth: AuthCategoryBehavior?, + authModeStrategy: AuthModeStrategy, + incomingSubscriptionEvents: IncomingSubscriptionEventPublisher? = nil + ) { self.modelReconciliationQueueSubject = PassthroughSubject() self.modelSchema = modelSchema MockModelReconciliationQueue.mockModelReconciliationQueues[modelSchema.name] = self diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockSQLiteStorageEngineAdapter.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockSQLiteStorageEngineAdapter.swift index dbdfdbf2a2..459ba8e884 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockSQLiteStorageEngineAdapter.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/Support/MockSQLiteStorageEngineAdapter.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore import Combine +import XCTest @testable import Amplify @testable import AWSDataStorePlugin @@ -81,66 +81,81 @@ class MockSQLiteStorageEngineAdapter: StorageEngineAdapter { // MARK: - StorageEngineAdapter - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: String, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) { + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: String, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) { XCTFail("Not expected to execute") } - - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) { + + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) { XCTFail("Not expected to execute") } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, completion: @escaping DataStoreCallback) where M: Model { + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) where M: Model { XCTFail("Not expected to execute") } - - func delete(untypedModelType modelType: Model.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: (DataStoreResult) -> Void) { + + func delete( + untypedModelType modelType: Model.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: (DataStoreResult) -> Void + ) { if let responder = responders[.deleteUntypedModel] as? DeleteUntypedModelCompletionResponder { let result = responder.callback((modelType, identifier.stringValue)) completion(result) return } - + return shouldReturnErrorOnDeleteMutation ? completion(.failure(causedBy: DataStoreError.invalidModelName("DelMutate"))) : completion(.emptyResult) } - func query(modelSchema: ModelSchema, - predicate: QueryPredicate?, - eagerLoad: Bool, - completion: DataStoreCallback<[Model]>) { + func query( + modelSchema: ModelSchema, + predicate: QueryPredicate?, + eagerLoad: Bool, + completion: DataStoreCallback<[Model]> + ) { let result = resultForQuery ?? .failure(DataStoreError.invalidOperation(causedBy: nil)) completion(result) } - func query(_ modelType: M.Type, - predicate: QueryPredicate?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: DataStoreCallback<[M]>) { + func query( + _ modelType: M.Type, + predicate: QueryPredicate?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: DataStoreCallback<[M]> + ) { XCTFail("Not expected to execute") } - func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: (DataStoreResult<[M]>) -> Void) { + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: (DataStoreResult<[M]>) -> Void + ) { XCTFail("Not expected to execute") } @@ -163,10 +178,12 @@ class MockSQLiteStorageEngineAdapter: StorageEngineAdapter { completion(resultForSave!) } - func save(_ model: M, - condition: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) { + func save( + _ model: M, + condition: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) { if let responder = responders[.saveModelCompletion] as? SaveModelCompletionResponder { responder.callback((model, completion)) return @@ -177,19 +194,23 @@ class MockSQLiteStorageEngineAdapter: StorageEngineAdapter { : completion(.success(model)) } - func save(_ model: M, - modelSchema: ModelSchema, - condition: QueryPredicate?, - eagerLoad: Bool) -> DataStoreResult { + func save( + _ model: M, + modelSchema: ModelSchema, + condition: QueryPredicate?, + eagerLoad: Bool + ) -> DataStoreResult { XCTFail("Not yet implemented") return .failure(.internalOperation("", "", nil)) } - func save(_ model: M, - modelSchema: ModelSchema, - condition where: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) { + func save( + _ model: M, + modelSchema: ModelSchema, + condition where: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) { if let responder = responders[.saveModelCompletion] as? SaveModelCompletionResponder { responder.callback((model, completion)) return @@ -205,12 +226,14 @@ class MockSQLiteStorageEngineAdapter: StorageEngineAdapter { return nil } - func query(_ modelType: M.Type, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: DataStoreCallback<[M]>) { + func query( + _ modelType: M.Type, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: DataStoreCallback<[M]> + ) { if let responder = responders[.queryModelTypePredicate] as? QueryModelTypePredicateResponder { let result = responder.callback((modelType, predicate)) @@ -297,12 +320,14 @@ class MockStorageEngineBehavior: StorageEngineBehavior { init() { } - init(isSyncEnabled: Bool, - dataStoreConfiguration: DataStoreConfiguration, - validAPIPluginKey: String = "awsAPIPlugin", - validAuthPluginKey: String = "awsCognitoAuthPlugin", - modelRegistryVersion: String, - userDefault: UserDefaults = UserDefaults.standard) throws { + init( + isSyncEnabled: Bool, + dataStoreConfiguration: DataStoreConfiguration, + validAPIPluginKey: String = "awsAPIPlugin", + validAuthPluginKey: String = "awsCognitoAuthPlugin", + modelRegistryVersion: String, + userDefault: UserDefaults = UserDefaults.standard + ) throws { } func setupPublisher() { @@ -355,50 +380,62 @@ class MockStorageEngineBehavior: StorageEngineBehavior { func applyModelMigrations(modelSchemas: [ModelSchema]) throws { } - func save(_ model: M, - condition: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) { + func save( + _ model: M, + condition: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) { XCTFail("Not expected to execute") } - func save(_ model: M, - modelSchema: ModelSchema, - condition where: QueryPredicate?, - eagerLoad: Bool, - completion: @escaping DataStoreCallback) { + func save( + _ model: M, + modelSchema: ModelSchema, + condition where: QueryPredicate?, + eagerLoad: Bool, + completion: @escaping DataStoreCallback + ) { XCTFail("Not expected to execute") } - - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withId id: String, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) { + + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withId id: String, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) { XCTFail("Not expected to execute") } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - filter: QueryPredicate, - completion: @escaping DataStoreCallback<[M]>) { + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + filter: QueryPredicate, + completion: @escaping DataStoreCallback<[M]> + ) { XCTFail("Not expected to execute") } - func delete(_ modelType: M.Type, - modelSchema: ModelSchema, - withIdentifier identifier: ModelIdentifierProtocol, - condition: QueryPredicate?, - completion: @escaping DataStoreCallback) where M: Model { + func delete( + _ modelType: M.Type, + modelSchema: ModelSchema, + withIdentifier identifier: ModelIdentifierProtocol, + condition: QueryPredicate?, + completion: @escaping DataStoreCallback + ) where M: Model { completion(.success(nil)) } - func query(_ modelType: M.Type, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: DataStoreCallback<[M]>) { + func query( + _ modelType: M.Type, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: DataStoreCallback<[M]> + ) { if let responder = responders[.query] as? QueryResponder { let result = responder.callback(()) completion(result) @@ -407,13 +444,15 @@ class MockStorageEngineBehavior: StorageEngineBehavior { } } - func query(_ modelType: M.Type, - modelSchema: ModelSchema, - predicate: QueryPredicate?, - sort: [QuerySortDescriptor]?, - paginationInput: QueryPaginationInput?, - eagerLoad: Bool, - completion: (DataStoreResult<[M]>) -> Void) { + func query( + _ modelType: M.Type, + modelSchema: ModelSchema, + predicate: QueryPredicate?, + sort: [QuerySortDescriptor]?, + paginationInput: QueryPaginationInput?, + eagerLoad: Bool, + completion: (DataStoreResult<[M]>) -> Void + ) { if let responder = responders[.query] as? QueryResponder { let result = responder.callback(()) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/AWSAuthorizationTypeIteratorTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/AWSAuthorizationTypeIteratorTests.swift index f07db70e2b..3e000ffc8a 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/AWSAuthorizationTypeIteratorTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/AWSAuthorizationTypeIteratorTests.swift @@ -5,27 +5,27 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore +import XCTest class AWSAuthorizationTypeIteratorTests: XCTestCase { - + func testEmptyIterator_hasNextValue_false() throws { var iterator = AWSAuthorizationTypeIterator(withValues: []) - + XCTAssertFalse(iterator.hasNext) XCTAssertNil(iterator.next()) } - + func testOneElementIterator_hasNextValue_once() throws { var iterator = AWSAuthorizationTypeIterator(withValues: [.designated(.amazonCognitoUserPools)]) XCTAssertTrue(iterator.hasNext) XCTAssertNotNil(iterator.next()) - + XCTAssertFalse(iterator.hasNext) } - + func testTwoElementsIterator_hasNextValue_twice() throws { var iterator = AWSAuthorizationTypeIterator(withValues: [ .designated(.amazonCognitoUserPools), @@ -34,10 +34,10 @@ class AWSAuthorizationTypeIteratorTests: XCTestCase { XCTAssertTrue(iterator.hasNext) XCTAssertNotNil(iterator.next()) - + XCTAssertTrue(iterator.hasNext) XCTAssertNotNil(iterator.next()) - + XCTAssertFalse(iterator.hasNext) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/ModelCompareTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/ModelCompareTests.swift index bac2f4e8ed..ec70db6641 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/ModelCompareTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/ModelCompareTests.swift @@ -25,20 +25,24 @@ class ModelCompareTests: BaseDataStoreTests { let draft = false let rating = 4.0 let status = PostStatus.published - let post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) - let post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + let post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) + let post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) XCTAssertTrue(Post.schema.compare(post1, post2)) } @@ -50,20 +54,24 @@ class ModelCompareTests: BaseDataStoreTests { let draft = false let rating = 4.0 let status = PostStatus.published - var post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) - var post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + var post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) + var post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) let commentId = UUID().uuidString let comment1 = Comment(id: commentId, content: "This is a comment.", createdAt: createdAt, post: post1) let comment2 = Comment(id: commentId, content: "This is a comment.", createdAt: createdAt, post: post2) @@ -81,20 +89,24 @@ class ModelCompareTests: BaseDataStoreTests { let status = PostStatus.published // creating posts with different id - var post1 = Post(id: UUID().uuidString, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) - var post2 = Post(id: UUID().uuidString, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + var post1 = Post( + id: UUID().uuidString, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) + var post2 = Post( + id: UUID().uuidString, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) let id = UUID().uuidString let comment1 = Comment(id: id, content: "This is a comment.", createdAt: createdAt, post: post1) let comment2 = Comment(id: id, content: "This is a comment.", createdAt: createdAt, post: post2) @@ -111,22 +123,26 @@ class ModelCompareTests: BaseDataStoreTests { let draft = false let rating = 4.0 let status = PostStatus.published - let post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + let post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) // rating is nil - let post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: nil, - status: status) + let post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: nil, + status: status + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } @@ -137,20 +153,24 @@ class ModelCompareTests: BaseDataStoreTests { let draft = false let rating = 4.0 let status = PostStatus.published - let post1 = Post(id: UUID().uuidString, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) - let post2 = Post(id: UUID().uuidString, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + let post1 = Post( + id: UUID().uuidString, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) + let post2 = Post( + id: UUID().uuidString, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } @@ -163,20 +183,24 @@ class ModelCompareTests: BaseDataStoreTests { let draft = false let rating = 4.0 let status = PostStatus.published - let post1 = Post(id: id, - title: title1, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) - let post2 = Post(id: id, - title: title2, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status) + let post1 = Post( + id: id, + title: title1, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) + let post2 = Post( + id: id, + title: title2, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } @@ -189,20 +213,24 @@ class ModelCompareTests: BaseDataStoreTests { let rating1 = 4.0 let rating2 = 1.0 let status = PostStatus.published - let post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating1, - status: status) - let post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating2, - status: status) + let post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating1, + status: status + ) + let post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating2, + status: status + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } @@ -247,20 +275,24 @@ class ModelCompareTests: BaseDataStoreTests { let rating = 4.0 let status1 = PostStatus.published let status2 = PostStatus.draft - let post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status1) - let post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft, - rating: rating, - status: status2) + let post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status1 + ) + let post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft, + rating: rating, + status: status2 + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } @@ -273,20 +305,24 @@ class ModelCompareTests: BaseDataStoreTests { let draft2 = true let rating = 4.0 let status = PostStatus.published - let post1 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft1, - rating: rating, - status: status) - let post2 = Post(id: id, - title: title, - content: content, - createdAt: createdAt, - draft: draft2, - rating: rating, - status: status) + let post1 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft1, + rating: rating, + status: status + ) + let post2 = Post( + id: id, + title: title, + content: content, + createdAt: createdAt, + draft: draft2, + rating: rating, + status: status + ) XCTAssertFalse(Post.schema.compare(post1, post2)) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift index 0add6aebd1..99a064d935 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift @@ -24,22 +24,28 @@ class MutationEventExtensionsTest: BaseDataStoreTests { func testSentModelWithNilVersion_Reconciled() async throws { let modelId = UUID().uuidString let post = Post(id: modelId, title: "title", content: "content", createdAt: .now()) - let requestMutationEvent = try createMutationEvent(model: post, - mutationType: .create, - createdAt: .now(), - version: nil, - inProcess: true) - let pendingMutationEvent = try createMutationEvent(model: post, - mutationType: .update, - createdAt: .now().add(value: 1, to: .second), - version: nil) + let requestMutationEvent = try createMutationEvent( + model: post, + mutationType: .create, + createdAt: .now(), + version: nil, + inProcess: true + ) + let pendingMutationEvent = try createMutationEvent( + model: post, + mutationType: .update, + createdAt: .now().add(value: 1, to: .second), + version: nil + ) let responseMutationSync = createMutationSync(model: post, version: 1) setUpPendingMutationQueue(post, [requestMutationEvent, pendingMutationEvent], pendingMutationEvent) - let reconciledEvent = MutationEvent.reconcile(pendingMutationEvent: pendingMutationEvent, - with: requestMutationEvent, - responseMutationSync: responseMutationSync) + let reconciledEvent = MutationEvent.reconcile( + pendingMutationEvent: pendingMutationEvent, + with: requestMutationEvent, + responseMutationSync: responseMutationSync + ) XCTAssertNotNil(reconciledEvent) XCTAssertEqual(reconciledEvent?.version, responseMutationSync.syncMetadata.version) @@ -47,9 +53,11 @@ class MutationEventExtensionsTest: BaseDataStoreTests { let updatingVersionExpectation = expectation(description: "update latest mutation event with response version") // update the version of head of mutation event table for given model id to the version of `mutationSync` - MutationEvent.reconcilePendingMutationEventsVersion(sent: requestMutationEvent, - received: responseMutationSync, - storageAdapter: storageAdapter) { result in + MutationEvent.reconcilePendingMutationEventsVersion( + sent: requestMutationEvent, + received: responseMutationSync, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -60,8 +68,10 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [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, - storageAdapter: storageAdapter) { result in + MutationEvent.pendingMutationEvents( + forModel: post, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -88,28 +98,38 @@ class MutationEventExtensionsTest: BaseDataStoreTests { func testSentModelWithNilVersion_SecondPendingEventNotReconciled() async throws { let modelId = UUID().uuidString let post = Post(id: modelId, title: "title", content: "content", createdAt: .now()) - let requestMutationEvent = try createMutationEvent(model: post, - mutationType: .create, - createdAt: .now(), - version: nil, - inProcess: true) - let pendingUpdateMutationEvent = try createMutationEvent(model: post, - mutationType: .update, - createdAt: .now().add(value: 1, to: .second), - version: nil) - let pendingDeleteMutationEvent = try createMutationEvent(model: post, - mutationType: .delete, - createdAt: .now().add(value: 2, to: .second), - version: nil) + let requestMutationEvent = try createMutationEvent( + model: post, + mutationType: .create, + createdAt: .now(), + version: nil, + inProcess: true + ) + let pendingUpdateMutationEvent = try createMutationEvent( + model: post, + mutationType: .update, + createdAt: .now().add(value: 1, to: .second), + version: nil + ) + let pendingDeleteMutationEvent = try createMutationEvent( + model: post, + mutationType: .delete, + createdAt: .now().add(value: 2, to: .second), + version: nil + ) let responseMutationSync = createMutationSync(model: post, version: 1) - setUpPendingMutationQueue(post, - [requestMutationEvent, pendingUpdateMutationEvent, pendingDeleteMutationEvent], - pendingUpdateMutationEvent) - - let reconciledEvent = MutationEvent.reconcile(pendingMutationEvent: pendingUpdateMutationEvent, - with: requestMutationEvent, - responseMutationSync: responseMutationSync) + setUpPendingMutationQueue( + post, + [requestMutationEvent, pendingUpdateMutationEvent, pendingDeleteMutationEvent], + pendingUpdateMutationEvent + ) + + let reconciledEvent = MutationEvent.reconcile( + pendingMutationEvent: pendingUpdateMutationEvent, + with: requestMutationEvent, + responseMutationSync: responseMutationSync + ) XCTAssertNotNil(reconciledEvent) XCTAssertEqual(reconciledEvent?.version, responseMutationSync.syncMetadata.version) @@ -117,9 +137,11 @@ class MutationEventExtensionsTest: BaseDataStoreTests { let updatingVersionExpectation = expectation(description: "update latest mutation event with response version") // update the version of head of mutation event table for given model id to the version of `mutationSync` - MutationEvent.reconcilePendingMutationEventsVersion(sent: requestMutationEvent, - received: responseMutationSync, - storageAdapter: storageAdapter) { result in + MutationEvent.reconcilePendingMutationEventsVersion( + sent: requestMutationEvent, + received: responseMutationSync, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -130,8 +152,10 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [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, - storageAdapter: storageAdapter) { result in + MutationEvent.pendingMutationEvents( + forModel: post, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -158,31 +182,39 @@ class MutationEventExtensionsTest: BaseDataStoreTests { let modelId = UUID().uuidString let post1 = Post(id: modelId, title: "title1", content: "content1", createdAt: .now()) let post2 = Post(id: modelId, title: "title2", content: "content2", createdAt: .now()) - let requestMutationEvent = try createMutationEvent(model: post1, - mutationType: .create, - createdAt: .now(), - version: 2, - inProcess: true) - let pendingMutationEvent = try createMutationEvent(model: post2, - mutationType: .update, - createdAt: .now().add(value: 1, to: .second), - version: 2) + let requestMutationEvent = try createMutationEvent( + model: post1, + mutationType: .create, + createdAt: .now(), + version: 2, + inProcess: true + ) + let pendingMutationEvent = try createMutationEvent( + model: post2, + mutationType: .update, + createdAt: .now().add(value: 1, to: .second), + version: 2 + ) let responseMutationSync = createMutationSync(model: post1, version: 1) setUpPendingMutationQueue(post1, [requestMutationEvent, pendingMutationEvent], pendingMutationEvent) - let reconciledEvent = MutationEvent.reconcile(pendingMutationEvent: pendingMutationEvent, - with: requestMutationEvent, - responseMutationSync: responseMutationSync) + let reconciledEvent = MutationEvent.reconcile( + pendingMutationEvent: pendingMutationEvent, + with: requestMutationEvent, + responseMutationSync: responseMutationSync + ) XCTAssertNil(reconciledEvent) let queryAfterUpdatingVersionExpectation = expectation(description: "update mutation should have version 2") let updatingVersionExpectation = expectation(description: "don't update latest mutation event with response version") - MutationEvent.reconcilePendingMutationEventsVersion(sent: requestMutationEvent, - received: responseMutationSync, - storageAdapter: storageAdapter) { result in + MutationEvent.reconcilePendingMutationEventsVersion( + sent: requestMutationEvent, + received: responseMutationSync, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -193,8 +225,10 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [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, - storageAdapter: storageAdapter) { result in + MutationEvent.pendingMutationEvents( + forModel: post1, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -221,31 +255,39 @@ class MutationEventExtensionsTest: BaseDataStoreTests { let post1 = Post(id: modelId, title: "title1", content: "content1", createdAt: .now()) let post2 = Post(id: modelId, title: "title2", content: "content2", createdAt: .now()) let post3 = Post(id: modelId, title: "title3", content: "content3", createdAt: .now()) - let requestMutationEvent = try createMutationEvent(model: post1, - mutationType: .update, - createdAt: .now(), - version: 1, - inProcess: true) - let pendingMutationEvent = try createMutationEvent(model: post2, - mutationType: .update, - createdAt: .now().add(value: 1, to: .second), - version: 1) + let requestMutationEvent = try createMutationEvent( + model: post1, + mutationType: .update, + createdAt: .now(), + version: 1, + inProcess: true + ) + let pendingMutationEvent = try createMutationEvent( + model: post2, + mutationType: .update, + createdAt: .now().add(value: 1, to: .second), + version: 1 + ) let responseMutationSync = createMutationSync(model: post3, version: 2) setUpPendingMutationQueue(post1, [requestMutationEvent, pendingMutationEvent], pendingMutationEvent) - let reconciledEvent = MutationEvent.reconcile(pendingMutationEvent: pendingMutationEvent, - with: requestMutationEvent, - responseMutationSync: responseMutationSync) + let reconciledEvent = MutationEvent.reconcile( + pendingMutationEvent: pendingMutationEvent, + with: requestMutationEvent, + responseMutationSync: responseMutationSync + ) XCTAssertNil(reconciledEvent) let queryAfterUpdatingVersionExpectation = expectation(description: "update mutation should have version 1") let updatingVersionExpectation = expectation(description: "don't update latest mutation event with response version") - MutationEvent.reconcilePendingMutationEventsVersion(sent: requestMutationEvent, - received: responseMutationSync, - storageAdapter: storageAdapter) { result in + MutationEvent.reconcilePendingMutationEventsVersion( + sent: requestMutationEvent, + received: responseMutationSync, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -256,8 +298,10 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [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, - storageAdapter: storageAdapter) { result in + MutationEvent.pendingMutationEvents( + forModel: post1, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -283,31 +327,39 @@ class MutationEventExtensionsTest: BaseDataStoreTests { let modelId = UUID().uuidString let post1 = Post(id: modelId, title: "title1", content: "content1", createdAt: .now()) let post2 = Post(id: modelId, title: "title2", content: "content2", createdAt: .now()) - let requestMutationEvent = try createMutationEvent(model: post1, - mutationType: .update, - createdAt: .now(), - version: 1, - inProcess: true) - let pendingMutationEvent = try createMutationEvent(model: post2, - mutationType: .update, - createdAt: .now().add(value: 1, to: .second), - version: 1) + let requestMutationEvent = try createMutationEvent( + model: post1, + mutationType: .update, + createdAt: .now(), + version: 1, + inProcess: true + ) + let pendingMutationEvent = try createMutationEvent( + model: post2, + mutationType: .update, + createdAt: .now().add(value: 1, to: .second), + version: 1 + ) let responseMutationSync = createMutationSync(model: post1, version: 2) setUpPendingMutationQueue(post1, [requestMutationEvent, pendingMutationEvent], pendingMutationEvent) - let reconciledEvent = MutationEvent.reconcile(pendingMutationEvent: pendingMutationEvent, - with: requestMutationEvent, - responseMutationSync: responseMutationSync) + let reconciledEvent = MutationEvent.reconcile( + pendingMutationEvent: pendingMutationEvent, + with: requestMutationEvent, + responseMutationSync: responseMutationSync + ) XCTAssertNotNil(reconciledEvent) XCTAssertEqual(reconciledEvent?.version, responseMutationSync.syncMetadata.version) let queryAfterUpdatingVersionExpectation = expectation(description: "update mutation should have version 2") let updatingVersionExpectation = expectation(description: "update latest mutation event with response version") - MutationEvent.reconcilePendingMutationEventsVersion(sent: requestMutationEvent, - received: responseMutationSync, - storageAdapter: storageAdapter) { result in + MutationEvent.reconcilePendingMutationEventsVersion( + sent: requestMutationEvent, + received: responseMutationSync, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -318,8 +370,10 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [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, - storageAdapter: storageAdapter) { result in + MutationEvent.pendingMutationEvents( + forModel: post1, + storageAdapter: storageAdapter + ) { result in switch result { case .failure(let error): XCTFail("Error : \(error)") @@ -336,33 +390,41 @@ class MutationEventExtensionsTest: BaseDataStoreTests { await fulfillment(of: [queryAfterUpdatingVersionExpectation], timeout: 1) } - private func createMutationEvent(model: Model, - mutationType: MutationEvent.MutationType, - createdAt: Temporal.DateTime, - version: Int? = nil, - inProcess: Bool = false) throws -> MutationEvent { - return MutationEvent(id: UUID().uuidString, - modelId: model.identifier(schema: MutationEvent.schema).stringValue, - modelName: model.modelName, - json: try model.toJSON(), - mutationType: mutationType, - createdAt: createdAt, - version: version, - inProcess: inProcess) + private func createMutationEvent( + model: Model, + mutationType: MutationEvent.MutationType, + createdAt: Temporal.DateTime, + version: Int? = nil, + inProcess: Bool = false + ) throws -> MutationEvent { + return try MutationEvent( + id: UUID().uuidString, + modelId: model.identifier(schema: MutationEvent.schema).stringValue, + modelName: model.modelName, + json: model.toJSON(), + mutationType: mutationType, + createdAt: createdAt, + version: version, + inProcess: inProcess + ) } private func createMutationSync(model: Model, version: Int = 1) -> MutationSync { - let metadata = MutationSyncMetadata(modelId: model.identifier(schema: MutationEvent.schema).stringValue, - modelName: model.modelName, - deleted: false, - lastChangedAt: Int64(Date().timeIntervalSince1970), - version: version) + let metadata = MutationSyncMetadata( + modelId: model.identifier(schema: MutationEvent.schema).stringValue, + modelName: model.modelName, + deleted: false, + lastChangedAt: Int64(Date().timeIntervalSince1970), + version: version + ) return MutationSync(model: AnyModel(model), syncMetadata: metadata) } - private func setUpPendingMutationQueue(_ model: Model, - _ mutationEvents: [MutationEvent], - _ expectedHeadOfQueue: MutationEvent) { + private func setUpPendingMutationQueue( + _ model: Model, + _ mutationEvents: [MutationEvent], + _ expectedHeadOfQueue: MutationEvent + ) { for mutationEvent in mutationEvents { let mutationEventSaveExpectation = expectation(description: "save mutation event success") storageAdapter.save(mutationEvent) { result in diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift index 2d91bccd89..d8a882c8ad 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift @@ -35,13 +35,17 @@ class BaseDataStoreTests: XCTestCase { storageAdapter = try SQLiteStorageEngineAdapter(connection: connection) try storageAdapter.setUp(modelSchemas: StorageEngine.systemModelSchemas) - let syncEngine = try RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault()) - storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let syncEngine = try RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault() + ) + storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) } catch { XCTFail(String(describing: error)) return @@ -50,11 +54,13 @@ class BaseDataStoreTests: XCTestCase { return self.storageEngine } let dataStorePublisher = DataStorePublisher() - dataStorePlugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: dataStorePublisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + dataStorePlugin = AWSDataStorePlugin( + modelRegistration: TestModelRegistration(), + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: dataStorePublisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let dataStoreConfig = DataStoreCategoryConfiguration(plugins: [ "awsDataStorePlugin": true diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/LocalStoreIntegrationTestBase.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/LocalStoreIntegrationTestBase.swift index 217db3315e..8eaaf9703c 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/LocalStoreIntegrationTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/LocalStoreIntegrationTestBase.swift @@ -15,15 +15,17 @@ class LocalStoreIntegrationTestBase: XCTestCase { override func setUp() async throws { await Amplify.reset() } - + func setUp(withModels models: AmplifyModelRegistration) { continueAfterFailure = false do { #if os(watchOS) - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: .subscriptionsDisabled)) + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: .subscriptionsDisabled + )) #else try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models)) #endif @@ -36,7 +38,7 @@ class LocalStoreIntegrationTestBase: XCTestCase { override func tearDown() async throws { let clearComplete = expectation(description: "clear completed") - + Task { try await Amplify.DataStore.clear() clearComplete.fulfill() diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSIncomingEventReconciliationQueue.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSIncomingEventReconciliationQueue.swift index 05b5750b8a..e165686fe0 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSIncomingEventReconciliationQueue.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSIncomingEventReconciliationQueue.swift @@ -14,11 +14,13 @@ import Combine class MockAWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueue { static let factory: IncomingEventReconciliationQueueFactory = { modelSchemas, api, storageAdapter, syncExpressions, auth, _, _, _ in - MockAWSIncomingEventReconciliationQueue(modelSchemas: modelSchemas, - api: api, - storageAdapter: storageAdapter, - syncExpressions: syncExpressions, - auth: auth) + MockAWSIncomingEventReconciliationQueue( + modelSchemas: modelSchemas, + api: api, + storageAdapter: storageAdapter, + syncExpressions: syncExpressions, + auth: auth + ) } let incomingEventSubject: PassthroughSubject var publisher: AnyPublisher { @@ -26,11 +28,13 @@ class MockAWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueue } static var lastInstance = AtomicValue(initialValue: nil) - init(modelSchemas: [ModelSchema], - api: APICategoryGraphQLBehavior?, - storageAdapter: StorageEngineAdapter?, - syncExpressions: [DataStoreSyncExpression], - auth: AuthCategoryBehavior?) { + init( + modelSchemas: [ModelSchema], + api: APICategoryGraphQLBehavior?, + storageAdapter: StorageEngineAdapter?, + syncExpressions: [DataStoreSyncExpression], + auth: AuthCategoryBehavior? + ) { self.incomingEventSubject = PassthroughSubject() updateLastInstance(instance: self) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSInitialSyncOrchestrator.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSInitialSyncOrchestrator.swift index 665938ce29..8954545c93 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSInitialSyncOrchestrator.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockAWSInitialSyncOrchestrator.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore import Combine +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -16,10 +16,12 @@ import Combine class MockAWSInitialSyncOrchestrator: InitialSyncOrchestrator { static let factory: InitialSyncOrchestratorFactory = { dataStoreConfiguration, _, api, reconciliationQueue, storageAdapter in - MockAWSInitialSyncOrchestrator(dataStoreConfiguration: dataStoreConfiguration, - api: api, - reconciliationQueue: reconciliationQueue, - storageAdapter: storageAdapter) + MockAWSInitialSyncOrchestrator( + dataStoreConfiguration: dataStoreConfiguration, + api: api, + reconciliationQueue: reconciliationQueue, + storageAdapter: storageAdapter + ) } typealias SyncOperationResult = Result @@ -33,10 +35,12 @@ class MockAWSInitialSyncOrchestrator: InitialSyncOrchestrator { return initialSyncOrchestratorTopic.eraseToAnyPublisher() } - init(dataStoreConfiguration: DataStoreConfiguration, - api: APICategoryGraphQLBehavior?, - reconciliationQueue: IncomingEventReconciliationQueue?, - storageAdapter: StorageEngineAdapter?) { + init( + dataStoreConfiguration: DataStoreConfiguration, + api: APICategoryGraphQLBehavior?, + reconciliationQueue: IncomingEventReconciliationQueue?, + storageAdapter: StorageEngineAdapter? + ) { self.initialSyncOrchestratorTopic = PassthroughSubject() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockFileManager.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockFileManager.swift index 50b4903aa7..bcf65bf1b4 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockFileManager.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockFileManager.swift @@ -24,7 +24,7 @@ class MockFileManager: FileManager { if hasError { throw MockFileManagerError.removeItemError } - if let removeItem = removeItem { + if let removeItem { removeItem(URL) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockOutgoingMutationQueue.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockOutgoingMutationQueue.swift index e0223bac2b..105b8c8f04 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockOutgoingMutationQueue.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockOutgoingMutationQueue.swift @@ -17,9 +17,11 @@ class MockOutgoingMutationQueue: OutgoingMutationQueueBehavior { completion() } - func startSyncingToCloud(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) { + func startSyncingToCloud( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { // no-op } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRemoteSyncEngine.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRemoteSyncEngine.swift index 1f2036784e..a3d9facc25 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRemoteSyncEngine.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRemoteSyncEngine.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore import Combine +import Foundation @testable import Amplify @testable import AmplifyTestCommon diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRequestRetryablePolicy.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRequestRetryablePolicy.swift index d8db743605..9f07e23116 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRequestRetryablePolicy.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockRequestRetryablePolicy.swift @@ -9,8 +9,8 @@ import Foundation @testable import Amplify @testable import AmplifyTestCommon -@testable import AWSPluginsCore @testable import AWSDataStorePlugin +@testable import AWSPluginsCore class MockRequestRetryablePolicy: RequestRetryablePolicy { @@ -25,9 +25,11 @@ class MockRequestRetryablePolicy: RequestRetryablePolicy { self.onRetryRequestAdvice = onRetryRequestAdvice } - override func retryRequestAdvice(urlError: URLError?, - httpURLResponse: HTTPURLResponse?, - attemptNumber: Int) -> RequestRetryAdvice { + override func retryRequestAdvice( + urlError: URLError?, + httpURLResponse: HTTPURLResponse?, + attemptNumber: Int + ) -> RequestRetryAdvice { onRetryRequestAdvice?(urlError, httpURLResponse, attemptNumber) // If this breaks, you didn't push anything onto the queue return !responseQueue.isEmpty ? responseQueue.removeFirst() : .init(shouldRetry: false) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockStateMachine.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockStateMachine.swift index c663505694..d975194840 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockStateMachine.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/MockStateMachine.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation @testable import AWSDataStorePlugin class MockStateMachine: StateMachine { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/NoOpMutationQueue.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/NoOpMutationQueue.swift index 82c9b031af..d6a85e624c 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/NoOpMutationQueue.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/NoOpMutationQueue.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import Amplify -@testable import AWSDataStorePlugin import AWSPluginsCore import Combine +@testable import Amplify +@testable import AWSDataStorePlugin /// A mutation queue that takes no action on either pause or start, to let these unit tests operate on the /// mutation queue without interference from the mutation queue polling for events and marking them in-process. @@ -17,9 +17,11 @@ class NoOpMutationQueue: OutgoingMutationQueueBehavior { completion() } - func startSyncingToCloud(api: APICategoryGraphQLBehavior, - mutationEventPublisher: MutationEventPublisher, - reconciliationQueue: IncomingEventReconciliationQueue?) { + func startSyncingToCloud( + api: APICategoryGraphQLBehavior, + mutationEventPublisher: MutationEventPublisher, + reconciliationQueue: IncomingEventReconciliationQueue? + ) { // do nothing } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/TestModelRegistration.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/TestModelRegistration.swift index 27e60a7ff2..21ca7256dc 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/TestModelRegistration.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/Mocks/TestModelRegistration.swift @@ -50,25 +50,33 @@ struct TestJsonModelRegistration: AmplifyModelRegistration { let draft = ModelField(name: "draft", type: .bool, isRequired: false) let rating = ModelField(name: "rating", type: .double, isRequired: false) let status = ModelField(name: "status", type: .string, isRequired: false) - let comments = ModelField(name: "comments", - type: .collection(of: "Comment"), - isRequired: false, - association: .hasMany(associatedFieldName: "post")) - let postSchema = ModelSchema(name: "Post", - listPluralName: "Posts", - syncPluralName: "Posts", - fields: [id.name: id, - title.name: title, - content.name: content, - createdAt.name: createdAt, - updatedAt.name: updatedAt, - draft.name: draft, - rating.name: rating, - status.name: status, - comments.name: comments]) - - ModelRegistry.register(modelType: DynamicModel.self, - modelSchema: postSchema) { (jsonString, decoder) -> Model in + let comments = ModelField( + name: "comments", + type: .collection(of: "Comment"), + isRequired: false, + association: .hasMany(associatedFieldName: "post") + ) + let postSchema = ModelSchema( + name: "Post", + listPluralName: "Posts", + syncPluralName: "Posts", + fields: [ + id.name: id, + title.name: title, + content.name: content, + createdAt.name: createdAt, + updatedAt.name: updatedAt, + draft.name: draft, + rating.name: rating, + status.name: status, + comments.name: comments + ] + ) + + ModelRegistry.register( + modelType: DynamicModel.self, + modelSchema: postSchema + ) { jsonString, decoder -> Model in try DynamicModel.from(json: jsonString, decoder: decoder) } @@ -77,20 +85,27 @@ struct TestJsonModelRegistration: AmplifyModelRegistration { let commentId = ModelFieldDefinition.id().modelField let commentContent = ModelField(name: "content", type: .string, isRequired: true) let commentCreatedAt = ModelField(name: "createdAt", type: .dateTime, isRequired: true) - let belongsTo = ModelField(name: "post", - type: .model(name: "Post"), - isRequired: true, - association: .belongsTo(associatedWith: nil, targetNames: ["postId"])) - let commentSchema = ModelSchema(name: "Comment", - listPluralName: "Comments", - syncPluralName: "Comments", - fields: [ - commentId.name: commentId, - commentContent.name: commentContent, - commentCreatedAt.name: commentCreatedAt, - belongsTo.name: belongsTo]) - ModelRegistry.register(modelType: DynamicModel.self, - modelSchema: commentSchema) { (jsonString, decoder) -> Model in + let belongsTo = ModelField( + name: "post", + type: .model(name: "Post"), + isRequired: true, + association: .belongsTo(associatedWith: nil, targetNames: ["postId"]) + ) + let commentSchema = ModelSchema( + name: "Comment", + listPluralName: "Comments", + syncPluralName: "Comments", + fields: [ + commentId.name: commentId, + commentContent.name: commentContent, + commentCreatedAt.name: commentCreatedAt, + belongsTo.name: belongsTo + ] + ) + ModelRegistry.register( + modelType: DynamicModel.self, + modelSchema: commentSchema + ) { jsonString, decoder -> Model in try DynamicModel.from(json: jsonString, decoder: decoder) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift index d86b8ba8a4..9967b65333 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Combine import SQLite import XCTest -import Combine @testable import Amplify -@testable import AWSPluginsCore @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import AWSPluginsCore /// Base class for SyncEngine and sync-enabled DataStore tests class SyncEngineTestBase: XCTestCase { @@ -38,7 +38,7 @@ class SyncEngineTestBase: XCTestCase { var remoteSyncEngineSink: AnyCancellable! var requestRetryablePolicy: MockRequestRetryablePolicy! - + var token: UnsubscribeToken! // MARK: - Setup @@ -64,7 +64,7 @@ class SyncEngineTestBase: XCTestCase { amplifyConfig = AmplifyConfiguration(api: apiConfig, auth: authConfig, dataStore: dataStoreConfig) - if let reachabilityPublisher = reachabilityPublisher { + if let reachabilityPublisher { apiPlugin = MockAPICategoryPlugin( reachabilityPublisher: reachabilityPublisher ) @@ -76,7 +76,7 @@ class SyncEngineTestBase: XCTestCase { try Amplify.add(plugin: apiPlugin) try Amplify.add(plugin: authPlugin) } - + override func tearDown() async throws { amplifyConfig = nil apiPlugin = nil @@ -102,7 +102,7 @@ class SyncEngineTestBase: XCTestCase { ) throws { models.forEach { ModelRegistry.register(modelType: $0) } let resolvedConnection: Connection - if let connection = connection { + if let connection { resolvedConnection = connection } else { resolvedConnection = try Connection(.inMemory) @@ -122,24 +122,29 @@ class SyncEngineTestBase: XCTestCase { ) throws { let mutationDatabaseAdapter = try AWSMutationDatabaseAdapter(storageAdapter: storageAdapter) let awsMutationEventPublisher = AWSMutationEventPublisher(eventSource: mutationDatabaseAdapter) - stateMachine = StateMachine(initialState: .notStarted, - resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:)) - - syncEngine = RemoteSyncEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - authModeStrategy: AWSDefaultAuthModeStrategy(), - outgoingMutationQueue: mutationQueue, - mutationEventIngester: mutationDatabaseAdapter, - mutationEventPublisher: awsMutationEventPublisher, - initialSyncOrchestratorFactory: initialSyncOrchestratorFactory, - reconciliationQueueFactory: MockAWSIncomingEventReconciliationQueue.factory, - stateMachine: stateMachine, - networkReachabilityPublisher: reachabilityPublisher, - requestRetryablePolicy: requestRetryablePolicy) + stateMachine = StateMachine( + initialState: .notStarted, + resolver: RemoteSyncEngine.Resolver.resolve(currentState:action:) + ) + + syncEngine = RemoteSyncEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + authModeStrategy: AWSDefaultAuthModeStrategy(), + outgoingMutationQueue: mutationQueue, + mutationEventIngester: mutationDatabaseAdapter, + mutationEventPublisher: awsMutationEventPublisher, + initialSyncOrchestratorFactory: initialSyncOrchestratorFactory, + reconciliationQueueFactory: MockAWSIncomingEventReconciliationQueue.factory, + stateMachine: stateMachine, + networkReachabilityPublisher: reachabilityPublisher, + requestRetryablePolicy: requestRetryablePolicy + ) remoteSyncEngineSink = syncEngine .publisher - .sink(receiveCompletion: {_ in }, - receiveValue: { (event: RemoteSyncEngineEvent) in + .sink( + receiveCompletion: {_ in }, + receiveValue: { (event: RemoteSyncEngineEvent) in switch event { case .mutationsPaused: // Assume AWSIncomingEventReconciliationQueue succeeds in establishing connections @@ -149,25 +154,30 @@ class SyncEngineTestBase: XCTestCase { default: break } - }) + } + ) let validAPIPluginKey = "MockAPICategoryPlugin" let validAuthPluginKey = "MockAuthCategoryPlugin" - let storageEngine = StorageEngine(storageAdapter: storageAdapter, - dataStoreConfiguration: .testDefault(), - syncEngine: syncEngine, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let storageEngine = StorageEngine( + storageAdapter: storageAdapter, + dataStoreConfiguration: .testDefault(), + syncEngine: syncEngine, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) let storageEngineBehaviorFactory: StorageEngineBehaviorFactory = {_, _, _, _, _, _ throws in return storageEngine } let publisher = DataStorePublisher() - let dataStorePlugin = AWSDataStorePlugin(modelRegistration: modelRegistration, - storageEngineBehaviorFactory: storageEngineBehaviorFactory, - dataStorePublisher: publisher, - validAPIPluginKey: validAPIPluginKey, - validAuthPluginKey: validAuthPluginKey) + let dataStorePlugin = AWSDataStorePlugin( + modelRegistration: modelRegistration, + storageEngineBehaviorFactory: storageEngineBehaviorFactory, + dataStorePublisher: publisher, + validAPIPluginKey: validAPIPluginKey, + validAuthPluginKey: validAuthPluginKey + ) try Amplify.add(plugin: dataStorePlugin) } @@ -177,10 +187,10 @@ class SyncEngineTestBase: XCTestCase { try Amplify.configure(amplifyConfig) try await Amplify.DataStore.start() } - + /// Starts amplify by invoking `Amplify.configure(amplifyConfig)`, and waits to receive a `syncStarted` Hub message /// before returning. - private func startAmplifyAndWaitForSync(completion: @escaping (Swift.Result)->Void) { + private func startAmplifyAndWaitForSync(completion: @escaping (Swift.Result) -> Void) { token = Amplify.Hub.listen(to: .dataStore) { [weak self] payload in if payload.eventName == "DataStore.syncStarted" { if let token = self?.token { @@ -189,14 +199,14 @@ class SyncEngineTestBase: XCTestCase { } } } - - + + Task { guard try await HubListenerTestUtilities.waitForListener(with: token, timeout: 5.0) else { XCTFail("Never registered listener for sync started") return } - + do { try await startAmplify() } catch { @@ -204,7 +214,7 @@ class SyncEngineTestBase: XCTestCase { completion(.failure(error)) } } - + } /// Starts amplify by invoking `Amplify.configure(amplifyConfig)`, and waits to receive a `syncStarted` Hub message @@ -216,20 +226,24 @@ class SyncEngineTestBase: XCTestCase { } } } - + // MARK: - Data methods /// Saves a mutation event directly to StorageAdapter. Used for pre-populating database before tests - func saveMutationEvent(of mutationType: MutationEvent.MutationType, - for post: Post, - inProcess: Bool = false) throws { - let mutationEvent = try MutationEvent(id: SyncEngineTestBase.mutationEventId(for: post), - modelId: post.id, - modelName: post.modelName, - json: post.toJSON(), - mutationType: mutationType, - createdAt: .now(), - inProcess: inProcess) + func saveMutationEvent( + of mutationType: MutationEvent.MutationType, + for post: Post, + inProcess: Bool = false + ) throws { + let mutationEvent = try MutationEvent( + id: SyncEngineTestBase.mutationEventId(for: post), + modelId: post.id, + modelName: post.modelName, + json: post.toJSON(), + mutationType: mutationType, + createdAt: .now(), + inProcess: inProcess + ) let mutationEventSaved = expectation(description: "Preloaded mutation event saved") storageAdapter.save(mutationEvent) { result in diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreAuthBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreAuthBaseTest.swift index 13e860d851..0ca4e79566 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreAuthBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreAuthBaseTest.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import XCTest -import Combine -import AWSDataStorePlugin -import AWSPluginsCore import AWSAPIPlugin import AWSCognitoAuthPlugin +import AWSDataStorePlugin +import AWSPluginsCore +import Combine +import Foundation +import XCTest #if !os(watchOS) @testable import DataStoreHostApp #endif @@ -24,7 +24,7 @@ struct TestUser { } class AuthRecorderInterceptor: URLRequestInterceptor { - let awsAuthService: AWSAuthService = AWSAuthService() + let awsAuthService: AWSAuthService = .init() var consumedAuthTypes: Set = [] private let accessQueue = DispatchQueue(label: "com.amazon.AuthRecorderInterceptor.consumedAuthTypes") @@ -46,13 +46,13 @@ class AuthRecorderInterceptor: URLRequestInterceptor { recordAuthType(.apiKey) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, case let .success(claims) = awsAuthService.getTokenClaims(tokenString: authHeaderValue), let cognitoIss = claims["iss"] as? String, cognitoIss.contains("cognito") { recordAuthType(.amazonCognitoUserPools) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, authHeaderValue.starts(with: "AWS4-HMAC-SHA256") { recordAuthType(.awsIAM) } @@ -128,7 +128,8 @@ class AWSDataStoreAuthBaseTest: XCTestCase { guard let user1 = credentials["user1"], let user2 = credentials["user2"], let passwordUser1 = credentials["passwordUser1"], - let passwordUser2 = credentials["passwordUser2"] else { + let passwordUser2 = credentials["passwordUser2"] + else { XCTFail("Invalid \(credentialsFile).json data") return } @@ -148,7 +149,8 @@ class AWSDataStoreAuthBaseTest: XCTestCase { func apiEndpointName() throws -> String { guard let apiPlugin = amplifyConfig.api?.plugins["awsAPIPlugin"], - case .object(let value) = apiPlugin else { + case .object(let value) = apiPlugin + else { throw APIError.invalidConfiguration("API endpoint not found.", "Check the provided configuration") } return value.keys.first! @@ -176,8 +178,10 @@ class AWSDataStoreAuthBaseTest: XCTestCase { authModeStrategy: testType.authStrategy ) #endif - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: datastoreConfig)) + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: datastoreConfig + )) let apiPlugin = apiPluginFactory() @@ -207,16 +211,21 @@ class AWSDataStoreAuthBaseTest: XCTestCase { extension AWSDataStoreAuthBaseTest { /// Signin given user /// - Parameter user - func signIn(user: TestUser?, - file: StaticString = #file, - line: UInt = #line) async throws { - guard let user = user else { + func signIn( + user: TestUser?, + file: StaticString = #file, + line: UInt = #line + ) async throws { + guard let user else { XCTFail("Invalid user", file: file, line: line) return } do { - let response = try await Amplify.Auth.signIn(username: user.username, - password: user.password, options: nil) + let response = try await Amplify.Auth.signIn( + username: user.username, + password: user.password, + options: nil + ) print("received response for signIn \(response)") let isSignedIn = try await isSignedIn() XCTAssert(isSignedIn) @@ -227,8 +236,10 @@ extension AWSDataStoreAuthBaseTest { } /// Signout current signed-in user - func signOut(file: StaticString = #file, - line: UInt = #line) async throws { + func signOut( + file: StaticString = #file, + line: UInt = #line + ) async throws { do { _ = await Amplify.Auth.signOut() print("signOut successfull") @@ -249,7 +260,7 @@ extension AWSDataStoreAuthBaseTest { throw error } } - + func getUserSub() async throws -> String { do { let authSession = try await Amplify.Auth.fetchAuthSession() @@ -264,7 +275,7 @@ extension AWSDataStoreAuthBaseTest { throw error } } - + func getIdentityId() async throws -> String! { do { let authSession = try await Amplify.Auth.fetchAuthSession() @@ -280,10 +291,12 @@ extension AWSDataStoreAuthBaseTest { } } - func queryModel(_ model: M.Type, - byId id: String, - file: StaticString = #file, - line: UInt = #line) async throws -> M? { + func queryModel( + _ model: M.Type, + byId id: String, + file: StaticString = #file, + line: UInt = #line + ) async throws -> M? { return try await Amplify.DataStore.query(M.self, byId: id) } } @@ -295,9 +308,11 @@ extension AWSDataStoreAuthBaseTest { /// - modelType: model type /// - expectation: success XCTestExpectation /// - onFailure: on failure callback - func assertQuerySuccess(modelType: M.Type, - _ expectations: AuthTestExpectations, - onFailure: @escaping (_ error: DataStoreError) -> Void) async throws { + func assertQuerySuccess( + modelType: (some Model).Type, + _ expectations: AuthTestExpectations, + onFailure: @escaping (_ error: DataStoreError) -> Void + ) async throws { Task { do { let posts = try await Amplify.DataStore.query(modelType) @@ -309,7 +324,7 @@ extension AWSDataStoreAuthBaseTest { } await fulfillment(of: [expectations.query], timeout: 60) } - + /// Asserts that DataStore is in a ready state and subscriptions are established /// - Parameter events: DataStore Hub events func assertDataStoreReady( @@ -334,28 +349,32 @@ extension AWSDataStoreAuthBaseTest { expectations.modelsSynced.fulfill() } } - + if event.eventName == dataStoreEvents.ready { expectations.ready.fulfill() } } .store(in: &requests) - + try await Amplify.DataStore.start() - - await fulfillment(of: [expectations.subscriptionsEstablished, - expectations.modelsSynced, - expectations.ready], - timeout: 60) + + await fulfillment( + of: [ + expectations.subscriptionsEstablished, + expectations.modelsSynced, + expectations.ready + ], + timeout: 60 + ) } - + /// Assert that a save and a delete mutation complete successfully. /// - Parameters: /// - model: model instance saved and then deleted /// - expectations: test expectations /// - onFailure: failure callback - func assertMutations( - model: M, + func assertMutations( + model: some Model, _ expectations: AuthTestExpectations, onFailure: @escaping (_ error: DataStoreError) -> Void ) async throws { @@ -366,7 +385,8 @@ extension AWSDataStoreAuthBaseTest { .filter { $0.eventName == HubPayload.EventName.DataStore.syncReceived } .sink { payload in guard let mutationEvent = payload.data as? MutationEvent, - mutationEvent.modelId == model.identifier else { + mutationEvent.modelId == model.identifier + else { return } @@ -390,8 +410,10 @@ extension AWSDataStoreAuthBaseTest { onFailure(error) } } - await fulfillment(of: [expectations.mutationSave, - expectations.mutationSaveProcessed], timeout: 60) + await fulfillment(of: [ + expectations.mutationSave, + expectations.mutationSaveProcessed + ], timeout: 60) Task { do { let deletedposts: () = try await Amplify.DataStore.delete(model) @@ -401,17 +423,23 @@ extension AWSDataStoreAuthBaseTest { onFailure(error) } } - await fulfillment(of: [expectations.mutationDelete, - expectations.mutationDeleteProcessed], timeout: 60) + await fulfillment(of: [ + expectations.mutationDelete, + expectations.mutationDeleteProcessed + ], timeout: 60) } - func assertUsedAuthTypes(_ authTypes: [AWSAuthorizationType], - file: StaticString = #file, - line: UInt = #line) { - XCTAssertEqual(authRecorderInterceptor.consumedAuthTypes, - Set(authTypes), - file: file, - line: line) + func assertUsedAuthTypes( + _ authTypes: [AWSAuthorizationType], + file: StaticString = #file, + line: UInt = #line + ) { + XCTAssertEqual( + authRecorderInterceptor.consumedAuthTypes, + Set(authTypes), + file: file, + line: line + ) } } @@ -427,11 +455,12 @@ extension AWSDataStoreAuthBaseTest { var mutationDeleteProcessed: XCTestExpectation var ready: XCTestExpectation var expectations: [XCTestExpectation] { - return [subscriptionsEstablished, - modelsSynced, - query, - mutationSave, - mutationSaveProcessed + return [ + subscriptionsEstablished, + modelsSynced, + query, + mutationSave, + mutationSaveProcessed ] } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests+Support.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests+Support.swift index b2292f96ed..5343425336 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests+Support.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests+Support.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import AWSPluginsCore import Amplify +import AWSPluginsCore +import XCTest #if !os(watchOS) import DataStoreHostApp #endif extension AWSDataStoreCategoryPluginAuthIntegrationTests { - func saveModel(_ model: T) async throws { + func saveModel(_ model: some Model) async throws { let localSaveInvoked = expectation(description: "local model was saved") Task { do { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests.swift index 948a417295..70515e9d5b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthIntegrationTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSDataStorePlugin +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp @@ -44,7 +44,8 @@ class AWSDataStoreCategoryPluginAuthIntegrationTests: AWSDataStoreAuthBaseTest { var remoteTodoOptional: TodoExplicitOwnerField? let syncReceivedListener = Amplify.Hub.listen(to: .dataStore, eventName: syncReceived) { payload in guard let mutationEvent = payload.data as? MutationEvent, - let todo = try? mutationEvent.decodeModel() as? TodoExplicitOwnerField else { + let todo = try? mutationEvent.decodeModel() as? TodoExplicitOwnerField + else { print("Can't cast payload as mutation event") return } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthOwnerIntegrationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthOwnerIntegrationTests.swift index aef8908f97..71b33a62c9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthOwnerIntegrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/AWSDataStoreCategoryPluginAuthOwnerIntegrationTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore +import XCTest @testable import Amplify class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseTest { @@ -16,8 +16,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testImplicitCustomOwner() async throws { - try await setup(withModels: CustomOwnerImplicitModelRegistration(), - testType: .defaultAuthCognito) + try await setup( + withModels: CustomOwnerImplicitModelRegistration(), + testType: .defaultAuthCognito + ) try await signIn(user: user1) @@ -26,8 +28,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT try await assertDataStoreReady(expectations) // Query - try await assertQuerySuccess(modelType: TodoCustomOwnerImplicit.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoCustomOwnerImplicit.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -46,8 +50,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testExplicitCustomOwner() async throws { - try await setup(withModels: CustomOwnerExplicitModelRegistration(), - testType: .defaultAuthCognito) + try await setup( + withModels: CustomOwnerExplicitModelRegistration(), + testType: .defaultAuthCognito + ) try await signIn(user: user1) @@ -56,8 +62,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT try await assertDataStoreReady(expectations) // Query - try await assertQuerySuccess(modelType: TodoCustomOwnerExplicit.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoCustomOwnerExplicit.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -76,8 +84,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testExplicitOwner() async throws { - try await setup(withModels: ExplicitOwnerModelRegistration(), - testType: .defaultAuthCognito) + try await setup( + withModels: ExplicitOwnerModelRegistration(), + testType: .defaultAuthCognito + ) try await signIn(user: user1) @@ -86,60 +96,68 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT try await assertDataStoreReady(expectations) // Query - try await assertQuerySuccess(modelType: TodoExplicitOwnerField.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoExplicitOwnerField.self, + expectations + ) { error in XCTFail("Error query \(error)") } let todo = TodoExplicitOwnerField(content: "content") - + // Mutations try await assertMutations(model: todo, expectations) { error in XCTFail("Error mutation \(error)") } - + assertUsedAuthTypes([.amazonCognitoUserPools]) } - + /// Given: a user signed in with CognitoUserPools, a model with multiple rules with /// explicit owner field /// When: DataStore query/mutation operations are sent with CognitoUserPools /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testExplicitMultipleOwner() async throws { - try await setup(withModels: ExplicitMultipleOwnerModelRegistration(), - testType: .defaultAuthCognito) - + try await setup( + withModels: ExplicitMultipleOwnerModelRegistration(), + testType: .defaultAuthCognito + ) + try await signIn(user: user1) - + let expectations = makeExpectations() - + try await assertDataStoreReady(expectations) - + // Query - try await assertQuerySuccess(modelType: TodoCognitoMultiOwner.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoCognitoMultiOwner.self, + expectations + ) { error in XCTFail("Error query \(error)") } - + let post = TodoCognitoMultiOwner(title: "title") - + // Mutations try await assertMutations(model: post, expectations) { error in XCTFail("Error mutation \(error)") } - + assertUsedAuthTypes([.amazonCognitoUserPools]) } - + /// Given: a user signed in with CognitoUserPools, a model with an implicit owner field /// When: DataStore query/mutation operations are sent with CognitoUserPools /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testImplicitOwner() async throws { - try await setup(withModels: ImplicitOwnerModelRegistration(), - testType: .defaultAuthCognito) + try await setup( + withModels: ImplicitOwnerModelRegistration(), + testType: .defaultAuthCognito + ) try await signIn(user: user1) @@ -148,8 +166,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT try await assertDataStoreReady(expectations) // Query - try await assertQuerySuccess(modelType: TodoImplicitOwnerField.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoImplicitOwnerField.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -168,8 +188,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT /// Then: DataStore is successfully initialized, query returns a result, /// mutation is processed for an authenticated users func testAllowPrivate() async throws { - try await setup(withModels: AllowPrivateModelRegistration(), - testType: .defaultAuthCognito) + try await setup( + withModels: AllowPrivateModelRegistration(), + testType: .defaultAuthCognito + ) try await signIn(user: user1) @@ -178,8 +200,10 @@ class AWSDataStoreCategoryPluginAuthOwnerIntegrationTests: AWSDataStoreAuthBaseT try await assertDataStoreReady(expectations) // Query - try await assertQuerySuccess(modelType: TodoCognitoPrivate.self, - expectations) { error in + try await assertQuerySuccess( + modelType: TodoCognitoPrivate.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -225,7 +249,7 @@ extension AWSDataStoreCategoryPluginAuthOwnerIntegrationTests { ModelRegistry.register(modelType: TodoCognitoMultiOwner.self) } } - + struct ImplicitOwnerModelRegistration: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner+Schema.swift index a42c5ea85a..1d4ead4562 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension TodoCognitoMultiOwner { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension TodoCognitoMultiOwner { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case content @@ -20,25 +20,25 @@ extension TodoCognitoMultiOwner { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let todoCognitoMultiOwner = TodoCognitoMultiOwner.keys - + model.authRules = [ rule(allow: .owner, ownerField: "owner", identityClaim: "cognito:username", provider: .userPools, operations: [.create, .update, .delete, .read]), rule(allow: .owner, ownerField: "editors", identityClaim: "cognito:username", provider: .userPools, operations: [.update, .read]) ] - + model.listPluralName = "TodoCognitoMultiOwners" model.syncPluralName = "TodoCognitoMultiOwners" - + model.attributes( .primaryKey(fields: [todoCognitoMultiOwner.id]) ) - + model.fields( .field(todoCognitoMultiOwner.id, is: .required, ofType: .string), .field(todoCognitoMultiOwner.title, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner.swift index ad45c098b8..3042046b21 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoMultiOwner.swift @@ -17,27 +17,33 @@ public struct TodoCognitoMultiOwner: Model { public var editors: [String?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - content: String? = nil, - owner: String? = nil, - editors: [String?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + content: String? = nil, + owner: String? = nil, + editors: [String?]? = nil + ) { + self.init( + id: id, title: title, content: content, owner: owner, editors: editors, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - content: String? = nil, - owner: String? = nil, - editors: [String?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + content: String? = nil, + owner: String? = nil, + editors: [String?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate+Schema.swift index 27b73152a8..2e1435be6a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate+Schema.swift @@ -9,32 +9,32 @@ import Amplify import Foundation -extension TodoCognitoPrivate { +public extension TodoCognitoPrivate { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let todoCognitoPrivate = TodoCognitoPrivate.keys - + model.authRules = [ rule(allow: .private, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "TodoCognitoPrivates" model.syncPluralName = "TodoCognitoPrivates" - + model.attributes( .primaryKey(fields: [todoCognitoPrivate.id]) ) - + model.fields( .field(todoCognitoPrivate.id, is: .required, ofType: .string), .field(todoCognitoPrivate.title, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate.swift index a25e488232..efb65dc817 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCognitoPrivate.swift @@ -15,17 +15,23 @@ public struct TodoCognitoPrivate: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String + ) { + self.init( + id: id, title: title, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit+Schema.swift index 3688748647..cd91d9eabf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit+Schema.swift @@ -9,33 +9,33 @@ import Amplify import Foundation -extension TodoCustomOwnerExplicit { +public extension TodoCustomOwnerExplicit { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case dominus case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let todoCustomOwnerExplicit = TodoCustomOwnerExplicit.keys - + model.authRules = [ rule(allow: .owner, ownerField: "dominus", identityClaim: "cognito:username", provider: .userPools, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "TodoCustomOwnerExplicits" model.syncPluralName = "TodoCustomOwnerExplicits" - + model.attributes( .primaryKey(fields: [todoCustomOwnerExplicit.id]) ) - + model.fields( .field(todoCustomOwnerExplicit.id, is: .required, ofType: .string), .field(todoCustomOwnerExplicit.title, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit.swift index b55124bbc1..dc848b009c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerExplicit.swift @@ -16,20 +16,26 @@ public struct TodoCustomOwnerExplicit: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - dominus: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + dominus: String? = nil + ) { + self.init( + id: id, title: title, dominus: dominus, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - dominus: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + dominus: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.dominus = dominus diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit+Schema.swift index 4aa97d8ab0..74061eda96 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit+Schema.swift @@ -9,32 +9,32 @@ import Amplify import Foundation -extension TodoCustomOwnerImplicit { +public extension TodoCustomOwnerImplicit { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let todoCustomOwnerImplicit = TodoCustomOwnerImplicit.keys - + model.authRules = [ rule(allow: .owner, ownerField: "dominus", identityClaim: "cognito:username", provider: .userPools, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "TodoCustomOwnerImplicits" model.syncPluralName = "TodoCustomOwnerImplicits" - + model.attributes( .primaryKey(fields: [todoCustomOwnerImplicit.id]) ) - + model.fields( .field(todoCustomOwnerImplicit.id, is: .required, ofType: .string), .field(todoCustomOwnerImplicit.title, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit.swift index 81e5db2f86..6e99122e71 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoCustomOwnerImplicit.swift @@ -15,17 +15,23 @@ public struct TodoCustomOwnerImplicit: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String + ) { + self.init( + id: id, title: title, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField+Schema.swift index c31e9d89a0..f775d485cd 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField+Schema.swift @@ -9,33 +9,33 @@ import Amplify import Foundation -extension TodoExplicitOwnerField { +public extension TodoExplicitOwnerField { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case owner case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let todoExplicitOwnerField = TodoExplicitOwnerField.keys - + model.authRules = [ rule(allow: .owner, ownerField: "owner", identityClaim: "cognito:username", provider: .userPools, operations: [.read, .create, .update, .delete]) ] - + model.listPluralName = "TodoExplicitOwnerFields" model.syncPluralName = "TodoExplicitOwnerFields" - + model.attributes( .primaryKey(fields: [todoExplicitOwnerField.id]) ) - + model.fields( .field(todoExplicitOwnerField.id, is: .required, ofType: .string), .field(todoExplicitOwnerField.content, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField.swift index c5b207683c..898110f10c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoExplicitOwnerField.swift @@ -16,20 +16,26 @@ public struct TodoExplicitOwnerField: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String, - owner: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + owner: String? = nil + ) { + self.init( + id: id, content: content, owner: owner, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - owner: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + owner: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.owner = owner diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField+Schema.swift index 4c4faa491f..07f5860aa4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField+Schema.swift @@ -9,32 +9,32 @@ import Amplify import Foundation -extension TodoImplicitOwnerField { +public extension TodoImplicitOwnerField { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let todoImplicitOwnerField = TodoImplicitOwnerField.keys - + model.authRules = [ rule(allow: .owner, ownerField: "owner", identityClaim: "cognito:username", provider: .userPools, operations: [.create, .update, .delete, .read]) ] - + model.listPluralName = "TodoImplicitOwnerFields" model.syncPluralName = "TodoImplicitOwnerFields" - + model.attributes( .primaryKey(fields: [todoImplicitOwnerField.id]) ) - + model.fields( .field(todoImplicitOwnerField.id, is: .required, ofType: .string), .field(todoImplicitOwnerField.content, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField.swift index 9d74762f6b..805b2c8cfe 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthCognitoTests/Models/TodoImplicitOwnerField.swift @@ -15,17 +15,23 @@ public struct TodoImplicitOwnerField: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreAuthBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreAuthBaseTest.swift index 8f89a32442..98904d0573 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreAuthBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreAuthBaseTest.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import XCTest -import Combine -import AWSDataStorePlugin -import AWSPluginsCore import AWSAPIPlugin import AWSCognitoAuthPlugin +import AWSDataStorePlugin +import AWSPluginsCore +import Combine +import Foundation +import XCTest #if !os(watchOS) @testable import DataStoreHostApp @@ -47,13 +47,13 @@ class DataStoreAuthBaseTestURLSessionFactory: URLSessionBehaviorFactory { result.insert(.apiKey) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, case let .success(claims) = AWSAuthService().getTokenClaims(tokenString: authHeaderValue), let cognitoIss = claims["iss"] as? String, cognitoIss.contains("cognito") { result.insert(.amazonCognitoUserPools) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, authHeaderValue.starts(with: "AWS4-HMAC-SHA256") { result.insert(.awsIAM) } @@ -88,9 +88,11 @@ class DataStoreAuthBaseTestURLSessionFactory: URLSessionBehaviorFactory { configuration.tlsMaximumSupportedProtocolVersion = .TLSv13 configuration.protocolClasses?.insert(Sniffer.self, at: 0) - let session = URLSession(configuration: configuration, - delegate: urlSessionDelegate, - delegateQueue: nil) + let session = URLSession( + configuration: configuration, + delegate: urlSessionDelegate, + delegateQueue: nil + ) return AmplifyURLSession(session: session) } @@ -200,8 +202,10 @@ class AWSDataStoreAuthBaseTest: XCTestCase { #else let datastoreConfig = DataStoreConfiguration.custom(authModeStrategy: testType.authStrategy) #endif - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: datastoreConfig)) + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: datastoreConfig + )) let apiPlugin = apiPluginFactory() @@ -234,40 +238,46 @@ class AWSDataStoreAuthBaseTest: XCTestCase { extension AWSDataStoreAuthBaseTest { /// Signin given user /// - Parameter user - func signIn(user: TestUser?, - file: StaticString = #file, - line: UInt = #line) async { - guard let user = user else { + func signIn( + user: TestUser?, + file: StaticString = #file, + line: UInt = #line + ) async { + guard let user else { XCTFail("Invalid user", file: file, line: line) return } let signInInvoked = expectation(description: "sign in completed") do { - _ = try await Amplify.Auth.signIn(username: user.username, - password: user.password, - options: nil) + _ = try await Amplify.Auth.signIn( + username: user.username, + password: user.password, + options: nil + ) signInInvoked.fulfill() - } catch(let error) { + } catch (let error) { XCTFail("Signin failure \(error)", file: file, line: line) signInInvoked.fulfill() // won't count as pass } await fulfillment(of: [signInInvoked], timeout: TestCommonConstants.networkTimeout) - + let signedIn = await isSignedIn() XCTAssert(signedIn, file: file, line: line) } /// Signout current signed-in user - func signOut(file: StaticString = #file, - line: UInt = #line) async { + func signOut( + file: StaticString = #file, + line: UInt = #line + ) async { let signoutInvoked = expectation(description: "sign out completed") Task { _ = await Amplify.Auth.signOut() signoutInvoked.fulfill() } - + await fulfillment(of: [signoutInvoked], timeout: TestCommonConstants.networkTimeout) - + let signedIn = await isSignedIn() XCTAssert(!signedIn, file: file, line: line) } @@ -279,10 +289,10 @@ extension AWSDataStoreAuthBaseTest { let authSession = try await Amplify.Auth.fetchAuthSession() resultOptional = authSession.isSignedIn checkIsSignedInCompleted.fulfill() - } catch(let error) { + } catch (let error) { fatalError("Failed to get auth session \(error)") } - + await fulfillment(of: [checkIsSignedInCompleted], timeout: TestCommonConstants.networkTimeout) guard let result = resultOptional else { XCTFail("Could not get isSignedIn for user") @@ -308,7 +318,7 @@ extension AWSDataStoreAuthBaseTest { case .failure(let error): XCTFail("Failed to get auth session \(error)") } - } catch(let error) { + } catch (let error) { XCTFail("Failed to get auth session \(error)") } @@ -337,7 +347,7 @@ extension AWSDataStoreAuthBaseTest { case .failure(let error): XCTFail("Failed to get auth session \(error)") } - } catch(let error) { + } catch (let error) { XCTFail("Failed to get auth session \(error)") } await fulfillment(of: [retrieveIdentityCompleted], timeout: TestCommonConstants.networkTimeout) @@ -349,10 +359,12 @@ extension AWSDataStoreAuthBaseTest { return result } - func queryModel(_ model: M.Type, - byId id: String, - file: StaticString = #file, - line: UInt = #line) async -> M? { + func queryModel( + _ model: M.Type, + byId id: String, + file: StaticString = #file, + line: UInt = #line + ) async -> M? { var queriedModel: M? let queriedInvoked = expectation(description: "Model queried") @@ -360,10 +372,10 @@ extension AWSDataStoreAuthBaseTest { let model = try await Amplify.DataStore.query(M.self, byId: id) queriedModel = model queriedInvoked.fulfill() - } catch(let error) { + } catch (let error) { XCTFail("Failed to query model \(error)", file: file, line: line) } - + await fulfillment(of: [queriedInvoked], timeout: TestCommonConstants.networkTimeout) return queriedModel } @@ -376,9 +388,11 @@ extension AWSDataStoreAuthBaseTest { /// - modelType: model type /// - expectation: success XCTestExpectation /// - onFailure: on failure callback - func assertQuerySuccess(modelType: M.Type, - _ expectations: AuthTestExpectations, - onFailure: @escaping (_ error: DataStoreError) -> Void) async { + func assertQuerySuccess( + modelType: (some Model).Type, + _ expectations: AuthTestExpectations, + onFailure: @escaping (_ error: DataStoreError) -> Void + ) async { Amplify.Publisher.create { try await Amplify.DataStore.query(modelType) }.sink { @@ -390,14 +404,18 @@ extension AWSDataStoreAuthBaseTest { XCTAssertNotNil(posts) expectations.query.fulfill() }.store(in: &requests) - await fulfillment(of: [expectations.query], - timeout: 60) + await fulfillment( + of: [expectations.query], + timeout: 60 + ) } /// Asserts that DataStore is in a ready state and subscriptions are established /// - Parameter events: DataStore Hub events - func assertDataStoreReady(_ expectations: AuthTestExpectations, - expectedModelSynced: Int = 1) async { + func assertDataStoreReady( + _ expectations: AuthTestExpectations, + expectedModelSynced: Int = 1 + ) async { var modelSyncedCount = 0 let dataStoreEvents = HubPayload.EventName.DataStore.self Amplify @@ -425,13 +443,17 @@ extension AWSDataStoreAuthBaseTest { do { try await Amplify.DataStore.start() - } catch(let error) { + } catch (let error) { XCTFail("Failure due to error: \(error)") } - await fulfillment(of: [expectations.subscriptionsEstablished, - expectations.modelsSynced, - expectations.ready], - timeout: 60) + await fulfillment( + of: [ + expectations.subscriptionsEstablished, + expectations.modelsSynced, + expectations.ready + ], + timeout: 60 + ) } /// Assert that a save and a delete mutation complete successfully. @@ -439,9 +461,11 @@ extension AWSDataStoreAuthBaseTest { /// - model: model instance saved and then deleted /// - expectations: test expectations /// - onFailure: failure callback - func assertMutations(model: M, - _ expectations: AuthTestExpectations, - onFailure: @escaping (_ error: DataStoreError) -> Void) async { + func assertMutations( + model: some Model, + _ expectations: AuthTestExpectations, + onFailure: @escaping (_ error: DataStoreError) -> Void + ) async { Amplify .Hub .publisher(for: .dataStore) @@ -504,7 +528,7 @@ extension AWSDataStoreAuthBaseTest { DataStoreAuthBaseTestURLSessionFactory.subject .filter { $0.0 == testId } .map { $0.1 } - .collect(.byTime(DispatchQueue.global(), .milliseconds(3500))) + .collect(.byTime(DispatchQueue.global(), .milliseconds(3_500))) .sink { let result = $0.reduce(Set()) { partialResult, data in partialResult.union(data) @@ -529,11 +553,12 @@ extension AWSDataStoreAuthBaseTest { var mutationDeleteProcessed: XCTestExpectation var ready: XCTestExpectation var expectations: [XCTestExpectation] { - return [subscriptionsEstablished, - modelsSynced, - query, - mutationSave, - mutationSaveProcessed + return [ + subscriptionsEstablished, + modelsSynced, + query, + mutationSave, + mutationSaveProcessed ] } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreCategoryPluginIAMAuthIntegrationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreCategoryPluginIAMAuthIntegrationTests.swift index 9216c48bcb..03d994848c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreCategoryPluginIAMAuthIntegrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/AWSDataStoreCategoryPluginIAMAuthIntegrationTests.swift @@ -17,9 +17,11 @@ class AWSDataStoreCategoryPluginIAMAuthIntegrationTests: AWSDataStoreAuthBaseTes /// mutation is processed for authenticated users func testIAMAllowPrivate() async { let testId = UUID().uuidString - await setup(withModels: IAMPrivateModelRegistration(), - testType: .defaultAuthIAM, - testId: testId) + await setup( + withModels: IAMPrivateModelRegistration(), + testType: .defaultAuthIAM, + testId: testId + ) await signIn(user: user1) @@ -30,8 +32,10 @@ class AWSDataStoreCategoryPluginIAMAuthIntegrationTests: AWSDataStoreAuthBaseTes let authTypeExpectation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: TodoIAMPrivate.self, - expectations) { error in + await assertQuerySuccess( + modelType: TodoIAMPrivate.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -51,9 +55,11 @@ class AWSDataStoreCategoryPluginIAMAuthIntegrationTests: AWSDataStoreAuthBaseTes /// mutation is processed for unauthenticated users func testIAMAllowPublic() async { let testId = UUID().uuidString - await setup(withModels: IAMPublicModelRegistration(), - testType: .defaultAuthIAM, - testId: testId) + await setup( + withModels: IAMPublicModelRegistration(), + testType: .defaultAuthIAM, + testId: testId + ) let expectations = makeExpectations() @@ -62,8 +68,10 @@ class AWSDataStoreCategoryPluginIAMAuthIntegrationTests: AWSDataStoreAuthBaseTes let authTypeExpectation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: TodoIAMPublic.self, - expectations) { error in + await assertQuerySuccess( + modelType: TodoIAMPublic.self, + expectations + ) { error in XCTFail("Error query \(error)") } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate+Schema.swift index acb4dec219..9268b9fcd1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate+Schema.swift @@ -9,23 +9,23 @@ import Amplify import Foundation -extension TodoIAMPrivate { +public extension TodoIAMPrivate { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoIAMPrivate = TodoIAMPrivate.keys model.authRules = [ - rule(allow: .private, provider: .iam, operations: [.create, .update, .delete, .read]) + rule(allow: .private, provider: .iam, operations: [.create, .update, .delete, .read]) ] model.pluralName = "TodoIAMPrivates" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate.swift index 767e06c1f4..b2323c498f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPrivate.swift @@ -15,17 +15,23 @@ public struct TodoIAMPrivate: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String + ) { + self.init( + id: id, title: title, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic+Schema.swift index 325dc5d7e4..6cc7819287 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension TodoIAMPublic { +public extension TodoIAMPublic { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoIAMPublic = TodoIAMPublic.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic.swift index ca128a8e1a..5bff04f220 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginAuthIAMTests/Models/TodoIAMPublic.swift @@ -15,17 +15,23 @@ public struct TodoIAMPublic: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String + ) { + self.init( + id: id, title: title, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4+Schema.swift index 6e27468d61..9062744e8e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case content case createdAt @@ -12,20 +19,20 @@ extension Comment4 { case post4CommentsPostId case post4CommentsTitle } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment4 = Comment4.keys - + model.pluralName = "Comment4s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .primaryKey(fields: [comment4.commentId, comment4.content]) ) - + model.fields( .field(comment4.commentId, is: .required, ofType: .string), .field(comment4.content, is: .required, ofType: .string), @@ -42,9 +49,11 @@ extension Comment4: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment4.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment4.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4.swift index bf249d1211..593b1efc60 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Comment4: Model { public var updatedAt: Temporal.DateTime? public var post4CommentsPostId: String? public var post4CommentsTitle: String? - - public init(commentId: String, - content: String, - post4CommentsPostId: String? = nil, - post4CommentsTitle: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + post4CommentsPostId: String? = nil, + post4CommentsTitle: String? = nil + ) { + self.init( + commentId: commentId, content: content, createdAt: nil, updatedAt: nil, post4CommentsPostId: post4CommentsPostId, - post4CommentsTitle: post4CommentsTitle) + post4CommentsTitle: post4CommentsTitle + ) } - internal init(commentId: String, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - post4CommentsPostId: String? = nil, - post4CommentsTitle: String? = nil) { + init( + commentId: String, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + post4CommentsPostId: String? = nil, + post4CommentsTitle: String? = nil + ) { self.commentId = commentId self.content = content self.createdAt = createdAt @@ -34,4 +47,4 @@ public struct Comment4: Model { self.post4CommentsPostId = post4CommentsPostId self.post4CommentsTitle = post4CommentsTitle } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7+Schema.swift index 7f15cca8e7..b04296095a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment7 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment7 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment7 = Comment7.keys - + model.pluralName = "Comment7s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .index(fields: ["postId", "postTitle"], name: "byPost"), .primaryKey(fields: [comment7.commentId, comment7.content]) ) - + model.fields( .field(comment7.commentId, is: .required, ofType: .string), .field(comment7.content, is: .required, ofType: .string), @@ -41,9 +48,11 @@ extension Comment7: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment7.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment7.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7.swift index bdf2ed40ce..57b5b11bbd 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment7.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Comment7: Model { public var post: Post7? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - content: String, - post: Post7? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + post: Post7? = nil + ) { + self.init( + commentId: commentId, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(commentId: String, - content: String, - post: Post7? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + content: String, + post: Post7? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.content = content self.post = post self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8+Schema.swift index 7bec3d9989..70d4be4f6e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case content case postId @@ -12,21 +19,21 @@ extension Comment8 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment8 = Comment8.keys - + model.pluralName = "Comment8s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .index(fields: ["postId", "postTitle"], name: "byPost"), .primaryKey(fields: [comment8.commentId, comment8.content]) ) - + model.fields( .field(comment8.commentId, is: .required, ofType: .string), .field(comment8.content, is: .required, ofType: .string), @@ -43,9 +50,11 @@ extension Comment8: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment8.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment8.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8.swift index 22fcd26a4b..0fc5456492 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Comment8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Comment8: Model { public var postTitle: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - content: String, - postId: String? = nil, - postTitle: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + postId: String? = nil, + postTitle: String? = nil + ) { + self.init( + commentId: commentId, content: content, postId: postId, postTitle: postTitle, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(commentId: String, - content: String, - postId: String? = nil, - postTitle: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + content: String, + postId: String? = nil, + postTitle: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.content = content self.postId = postId @@ -34,4 +47,4 @@ public struct Comment8: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex+Schema.swift index 777e8fe158..fae7029627 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CommentWithCompositeKeyAndIndex { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension CommentWithCompositeKeyAndIndex { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let commentWithCompositeKeyAndIndex = CommentWithCompositeKeyAndIndex.keys - + model.pluralName = "CommentWithCompositeKeyAndIndices" - + model.attributes( .index(fields: ["id", "content"], name: nil), .index(fields: ["postID", "postTitle"], name: "byPost"), .primaryKey(fields: [commentWithCompositeKeyAndIndex.id, commentWithCompositeKeyAndIndex.content]) ) - + model.fields( .field(commentWithCompositeKeyAndIndex.id, is: .required, ofType: .string), .field(commentWithCompositeKeyAndIndex.content, is: .required, ofType: .string), @@ -41,9 +48,11 @@ extension CommentWithCompositeKeyAndIndex: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CommentWithCompositeKeyAndIndex.IdentifierProtocol { - public static func identifier(id: String, - content: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "content", value: content)]) +public extension CommentWithCompositeKeyAndIndex.IdentifierProtocol { + static func identifier( + id: String, + content: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "content", value: content)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex.swift index 8f3562e1e0..595f98fa30 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyAndIndex.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct CommentWithCompositeKeyAndIndex: Model { public var post: PostWithCompositeKeyAndIndex? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKeyAndIndex? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKeyAndIndex? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKeyAndIndex? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKeyAndIndex? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional+Schema.swift index 91a30cf9de..4db364f449 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CommentWithCompositeKeyUnidirectional { +public extension CommentWithCompositeKeyUnidirectional { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt @@ -20,10 +20,10 @@ extension CommentWithCompositeKeyUnidirectional { case postWithCompositeKeyUnidirectionalCommentsTitle } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let commentWithCompositeKeyUnidirectional = CommentWithCompositeKeyUnidirectional.keys model.pluralName = "CommentWithCompositeKeyUnidirectionals" @@ -49,9 +49,11 @@ extension CommentWithCompositeKeyUnidirectional: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CommentWithCompositeKeyUnidirectional.IdentifierProtocol { - public static func identifier(id: String, - content: String) -> Self { +public extension CommentWithCompositeKeyUnidirectional.IdentifierProtocol { + static func identifier( + id: String, + content: String + ) -> Self { .make(fields: [(name: "id", value: id), (name: "content", value: content)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional.swift index 23617b6d3e..d3ea55a904 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/CommentWithCompositeKeyUnidirectional.swift @@ -17,23 +17,29 @@ public struct CommentWithCompositeKeyUnidirectional: Model { public var postWithCompositeKeyUnidirectionalCommentsId: String? public var postWithCompositeKeyUnidirectionalCommentsTitle: String? - public init(id: String = UUID().uuidString, - content: String, - post21CommentsId: String? = nil, - post21CommentsTitle: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + post21CommentsId: String? = nil, + post21CommentsTitle: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, updatedAt: nil, postWithCompositeKeyUnidirectionalCommentsId: post21CommentsId, - postWithCompositeKeyUnidirectionalCommentsTitle: post21CommentsTitle) + postWithCompositeKeyUnidirectionalCommentsTitle: post21CommentsTitle + ) } - internal init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - postWithCompositeKeyUnidirectionalCommentsId: String? = nil, - postWithCompositeKeyUnidirectionalCommentsTitle: String? = nil) { + init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + postWithCompositeKeyUnidirectionalCommentsId: String? = nil, + postWithCompositeKeyUnidirectionalCommentsTitle: String? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk+Schema.swift index e754bac1c7..6cd83a593f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelCompositeIntPk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelCompositeIntPk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case serial case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelCompositeIntPk = ModelCompositeIntPk.keys - + model.pluralName = "ModelCompositeIntPks" - + model.attributes( .index(fields: ["id", "serial"], name: nil), .primaryKey(fields: [modelCompositeIntPk.id, modelCompositeIntPk.serial]) ) - + model.fields( .field(modelCompositeIntPk.id, is: .required, ofType: .string), .field(modelCompositeIntPk.serial, is: .required, ofType: .int), @@ -38,9 +45,11 @@ extension ModelCompositeIntPk: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCompositeIntPk.IdentifierProtocol { - public static func identifier(id: String, - serial: Int) -> Self { - .make(fields:[(name: "id", value: id), (name: "serial", value: serial)]) +public extension ModelCompositeIntPk.IdentifierProtocol { + static func identifier( + id: String, + serial: Int + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "serial", value: serial)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk.swift index 35c6ea35ba..1af43fb97a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeIntPk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct ModelCompositeIntPk: Model { public let serial: Int public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - serial: Int) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + serial: Int + ) { + self.init( + id: id, serial: serial, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - serial: Int, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + serial: Int, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.serial = serial self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk+Schema.swift index 1a31fb3ce0..2106583e7c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelCompositeMultiplePk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelCompositeMultiplePk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case location case name @@ -12,20 +19,20 @@ extension ModelCompositeMultiplePk { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelCompositeMultiplePk = ModelCompositeMultiplePk.keys - + model.pluralName = "ModelCompositeMultiplePks" - + model.attributes( .index(fields: ["id", "location", "name"], name: nil), .primaryKey(fields: [modelCompositeMultiplePk.id, modelCompositeMultiplePk.location, modelCompositeMultiplePk.name]) ) - + model.fields( .field(modelCompositeMultiplePk.id, is: .required, ofType: .string), .field(modelCompositeMultiplePk.location, is: .required, ofType: .string), @@ -42,10 +49,12 @@ extension ModelCompositeMultiplePk: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCompositeMultiplePk.IdentifierProtocol { - public static func identifier(id: String, - location: String, - name: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "location", value: location), (name: "name", value: name)]) +public extension ModelCompositeMultiplePk.IdentifierProtocol { + static func identifier( + id: String, + location: String, + name: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "location", value: location), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk.swift index 238c7b2ba6..e75bb7aed9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositeMultiplePk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct ModelCompositeMultiplePk: Model { public var lastName: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - location: String, - name: String, - lastName: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + location: String, + name: String, + lastName: String? = nil + ) { + self.init( + id: id, location: location, name: name, lastName: lastName, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - location: String, - name: String, - lastName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + location: String, + name: String, + lastName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.location = location self.name = name @@ -34,4 +47,4 @@ public struct ModelCompositeMultiplePk: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk+Schema.swift index d166130aa2..db5b4bb923 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelCompositePk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelCompositePk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case dob case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelCompositePk = ModelCompositePk.keys - + model.pluralName = "ModelCompositePks" - + model.attributes( .index(fields: ["id", "dob"], name: nil), .primaryKey(fields: [modelCompositePk.id, modelCompositePk.dob]) ) - + model.fields( .field(modelCompositePk.id, is: .required, ofType: .string), .field(modelCompositePk.dob, is: .required, ofType: .dateTime), @@ -40,9 +47,11 @@ extension ModelCompositePk: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCompositePk.IdentifierProtocol { - public static func identifier(id: String, - dob: Temporal.DateTime) -> Self { - .make(fields:[(name: "id", value: id), (name: "dob", value: dob)]) +public extension ModelCompositePk.IdentifierProtocol { + static func identifier( + id: String, + dob: Temporal.DateTime + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "dob", value: dob)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk.swift index 21766fab12..98ce1635fa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct ModelCompositePk: Model { public var name: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil + ) { + self.init( + id: id, dob: dob, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo+Schema.swift index 525ecc5ce5..15d8123b26 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ModelCompositePkBelongsTo { +public extension ModelCompositePkBelongsTo { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dob case owner @@ -20,10 +20,10 @@ extension ModelCompositePkBelongsTo { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let modelCompositePkBelongsTo = ModelCompositePkBelongsTo.keys model.pluralName = "ModelCompositePkBelongsTos" @@ -33,17 +33,20 @@ extension ModelCompositePkBelongsTo { ) model.fields( - .field(modelCompositePkBelongsTo.id, is: .required, ofType: .string), - .field(modelCompositePkBelongsTo.dob, is: .required, ofType: .dateTime), - .field(modelCompositePkBelongsTo.name, is: .optional, ofType: .string), - .belongsTo(modelCompositePkBelongsTo.owner, is: .optional, - ofType: ModelCompositePkWithAssociation.self, - targetNames: [ - "modelCompositePkWithAssociationOtherModelsId", - "modelCompositePkWithAssociationOtherModelsDob" - ]), - .field(modelCompositePkBelongsTo.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), - .field(modelCompositePkBelongsTo.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) + .field(modelCompositePkBelongsTo.id, is: .required, ofType: .string), + .field(modelCompositePkBelongsTo.dob, is: .required, ofType: .dateTime), + .field(modelCompositePkBelongsTo.name, is: .optional, ofType: .string), + .belongsTo( + modelCompositePkBelongsTo.owner, + is: .optional, + ofType: ModelCompositePkWithAssociation.self, + targetNames: [ + "modelCompositePkWithAssociationOtherModelsId", + "modelCompositePkWithAssociationOtherModelsDob" + ] + ), + .field(modelCompositePkBelongsTo.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), + .field(modelCompositePkBelongsTo.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } } @@ -53,8 +56,8 @@ extension ModelCompositePkBelongsTo: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCompositePkBelongsTo.IdentifierProtocol { - public static func identifier(id: String, dob: Temporal.DateTime) -> Self { +public extension ModelCompositePkBelongsTo.IdentifierProtocol { + static func identifier(id: String, dob: Temporal.DateTime) -> Self { .make(fields: [(name: "id", value: id), (name: "dob", value: dob)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo.swift index 4d4817d0fc..8d9963a420 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkBelongsTo.swift @@ -17,23 +17,29 @@ public struct ModelCompositePkBelongsTo: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - owner: ModelCompositePkWithAssociation? = nil) { - self.init(id: id, - dob: dob, - name: name, - owner: owner, - createdAt: nil, - updatedAt: nil) + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + owner: ModelCompositePkWithAssociation? = nil + ) { + self.init( + id: id, + dob: dob, + name: name, + owner: owner, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - owner: ModelCompositePkWithAssociation? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + owner: ModelCompositePkWithAssociation? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.name = name diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation+Schema.swift index cbb3bc7f85..0ad5807f7e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ModelCompositePkWithAssociation { +public extension ModelCompositePkWithAssociation { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dob case name @@ -20,10 +20,10 @@ extension ModelCompositePkWithAssociation { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let modelCompositePkWithAssociation = ModelCompositePkWithAssociation.keys model.pluralName = "ModelCompositePkWithAssociations" @@ -36,10 +36,12 @@ extension ModelCompositePkWithAssociation { .field(modelCompositePkWithAssociation.id, is: .required, ofType: .string), .field(modelCompositePkWithAssociation.dob, is: .required, ofType: .dateTime), .field(modelCompositePkWithAssociation.name, is: .optional, ofType: .string), - .hasMany(modelCompositePkWithAssociation.otherModels, - is: .optional, - ofType: ModelCompositePkBelongsTo.self, - associatedWith: ModelCompositePkBelongsTo.keys.owner), + .hasMany( + modelCompositePkWithAssociation.otherModels, + is: .optional, + ofType: ModelCompositePkBelongsTo.self, + associatedWith: ModelCompositePkBelongsTo.keys.owner + ), .field(modelCompositePkWithAssociation.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), .field(modelCompositePkWithAssociation.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) @@ -51,8 +53,8 @@ extension ModelCompositePkWithAssociation: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCompositePkWithAssociation.IdentifierProtocol { - public static func identifier(id: String, dob: Temporal.DateTime) -> Self { +public extension ModelCompositePkWithAssociation.IdentifierProtocol { + static func identifier(id: String, dob: Temporal.DateTime) -> Self { .make(fields: [(name: "id", value: id), (name: "dob", value: dob)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation.swift index 810e0e9a3f..ece232844f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCompositePkWithAssociation.swift @@ -17,23 +17,29 @@ public struct ModelCompositePkWithAssociation: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - otherModels: List? = []) { - self.init(id: id, - dob: dob, - name: name, - otherModels: otherModels, - createdAt: nil, - updatedAt: nil) + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + otherModels: List? = [] + ) { + self.init( + id: id, + dob: dob, + name: name, + otherModels: otherModels, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - otherModels: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + otherModels: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.name = name diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPKDefined.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPKDefined.swift index 651ae307db..e658cbc193 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPKDefined.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPKDefined.swift @@ -16,20 +16,26 @@ public struct ModelCustomPkDefined: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil + ) { + self.init( + id: id, dob: dob, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - name: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + name: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.name = name diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPkDefined+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPkDefined+Schema.swift index 49c4b706a5..11809bb3f1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPkDefined+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelCustomPkDefined+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ModelCustomPkDefined { +public extension ModelCustomPkDefined { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dob case name @@ -19,10 +19,10 @@ extension ModelCustomPkDefined { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let modelCompositePk = ModelCustomPkDefined.keys model.pluralName = "ModelCustomPkDefined" @@ -48,8 +48,8 @@ extension ModelCustomPkDefined: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelCustomPkDefined.IdentifierProtocol { - public static func identifier(id: String, dob: Temporal.DateTime) -> Self { +public extension ModelCustomPkDefined.IdentifierProtocol { + static func identifier(id: String, dob: Temporal.DateTime) -> Self { .make(fields: [(name: "id", value: id), (name: "dob", value: dob)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk+Schema.swift index e01e1077e6..fe673e971b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelExplicitCustomPk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelExplicitCustomPk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case userId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelExplicitCustomPk = ModelExplicitCustomPk.keys - + model.pluralName = "ModelExplicitCustomPks" - + model.attributes( .index(fields: ["userId"], name: nil), .primaryKey(fields: [modelExplicitCustomPk.userId]) ) - + model.fields( .field(modelExplicitCustomPk.userId, is: .required, ofType: .string), .field(modelExplicitCustomPk.name, is: .optional, ofType: .string), @@ -38,8 +45,8 @@ extension ModelExplicitCustomPk: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ModelExplicitCustomPk.IdentifierProtocol { - public static func identifier(userId: String) -> Self { - .make(fields:[(name: "userId", value: userId)]) +public extension ModelExplicitCustomPk.IdentifierProtocol { + static func identifier(userId: String) -> Self { + .make(fields: [(name: "userId", value: userId)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk.swift index 59b1dc1359..a7b95653a5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitCustomPk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct ModelExplicitCustomPk: Model { public var name: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(userId: String, - name: String? = nil) { - self.init(userId: userId, + + public init( + userId: String, + name: String? = nil + ) { + self.init( + userId: userId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(userId: String, - name: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + userId: String, + name: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.userId = userId self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk+Schema.swift index 6752864fc3..0e3a76938d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelExplicitDefaultPk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelExplicitDefaultPk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelExplicitDefaultPk = ModelExplicitDefaultPk.keys - + model.pluralName = "ModelExplicitDefaultPks" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [modelExplicitDefaultPk.id]) ) - + model.fields( .field(modelExplicitDefaultPk.id, is: .required, ofType: .string), .field(modelExplicitDefaultPk.name, is: .optional, ofType: .string), @@ -36,4 +43,4 @@ extension ModelExplicitDefaultPk { extension ModelExplicitDefaultPk: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk.swift index b44e5e9377..880c718eff 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelExplicitDefaultPk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct ModelExplicitDefaultPk: Model { public var name: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String? = nil + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk+Schema.swift index 0fe7bb7ae2..a3db3c0163 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk+Schema.swift @@ -1,28 +1,35 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ModelImplicitDefaultPk { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ModelImplicitDefaultPk { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let modelImplicitDefaultPk = ModelImplicitDefaultPk.keys - + model.pluralName = "ModelImplicitDefaultPks" - + model.attributes( .primaryKey(fields: [modelImplicitDefaultPk.id]) ) - + model.fields( .field(modelImplicitDefaultPk.id, is: .required, ofType: .string), .field(modelImplicitDefaultPk.name, is: .optional, ofType: .string), @@ -35,4 +42,4 @@ extension ModelImplicitDefaultPk { extension ModelImplicitDefaultPk: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk.swift index a476abedf9..69fa2b17dc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/ModelImplicitDefaultPk.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct ModelImplicitDefaultPk: Model { public var name: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String? = nil + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4+Schema.swift index 0f9b9f5740..d1b37b849a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post4 = Post4.keys - + model.pluralName = "Post4s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post4.postId, post4.title]) ) - + model.fields( .field(post4.postId, is: .required, ofType: .string), .field(post4.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension Post4: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post4.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post4.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4.swift index a50849704b..1d08640c37 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7+Schema.swift index 7700f9207a..44dac0b093 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post7 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post7 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post7 = Post7.keys - + model.pluralName = "Post7s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post7.postId, post7.title]) ) - + model.fields( .field(post7.postId, is: .required, ofType: .string), .field(post7.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension Post7: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post7.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post7.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7.swift index 8cb750a96d..c07fbc8320 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post7.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post7: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8+Schema.swift index 520236fa1e..9a11351d9d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post8 = Post8.keys - + model.pluralName = "Post8s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post8.postId, post8.title]) ) - + model.fields( .field(post8.postId, is: .required, ofType: .string), .field(post8.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension Post8: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post8.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post8.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8.swift index 440cd2b9d7..eb60ae8287 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Post8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post8: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey+Schema.swift index 172936f4e8..1d03fc790d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostTagsWithCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension PostTagsWithCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case postWithTagsCompositeKey case tagWithCompositeKey case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let postTagsWithCompositeKey = PostTagsWithCompositeKey.keys - + model.pluralName = "PostTagsWithCompositeKeys" - + model.attributes( .index(fields: ["postWithTagsCompositeKeyPostId", "postWithTagsCompositeKeytitle"], name: "byPostWithTagsCompositeKey"), .index(fields: ["tagWithCompositeKeyId", "tagWithCompositeKeyname"], name: "byTagWithCompositeKey"), .primaryKey(fields: [postTagsWithCompositeKey.id]) ) - + model.fields( .field(postTagsWithCompositeKey.id, is: .required, ofType: .string), .belongsTo(postTagsWithCompositeKey.postWithTagsCompositeKey, is: .required, ofType: PostWithTagsCompositeKey.self, targetNames: ["postWithTagsCompositeKeyPostId", "postWithTagsCompositeKeytitle"]), @@ -39,4 +46,4 @@ extension PostTagsWithCompositeKey { extension PostTagsWithCompositeKey: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey.swift index d03e2b5e42..9bf3f2b9e0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostTagsWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostTagsWithCompositeKey: Model { public var tagWithCompositeKey: TagWithCompositeKey public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - postWithTagsCompositeKey: PostWithTagsCompositeKey, - tagWithCompositeKey: TagWithCompositeKey) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + postWithTagsCompositeKey: PostWithTagsCompositeKey, + tagWithCompositeKey: TagWithCompositeKey + ) { + self.init( + id: id, postWithTagsCompositeKey: postWithTagsCompositeKey, tagWithCompositeKey: tagWithCompositeKey, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - postWithTagsCompositeKey: PostWithTagsCompositeKey, - tagWithCompositeKey: TagWithCompositeKey, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + postWithTagsCompositeKey: PostWithTagsCompositeKey, + tagWithCompositeKey: TagWithCompositeKey, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.postWithTagsCompositeKey = postWithTagsCompositeKey self.tagWithCompositeKey = tagWithCompositeKey self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex+Schema.swift index 0f13a541b9..16b1d5f5c1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithCompositeKeyAndIndex { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension PostWithCompositeKeyAndIndex { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let postWithCompositeKeyAndIndex = PostWithCompositeKeyAndIndex.keys - + model.pluralName = "PostWithCompositeKeyAndIndices" - + model.attributes( .index(fields: ["id", "title"], name: nil), .primaryKey(fields: [postWithCompositeKeyAndIndex.id, postWithCompositeKeyAndIndex.title]) ) - + model.fields( .field(postWithCompositeKeyAndIndex.id, is: .required, ofType: .string), .field(postWithCompositeKeyAndIndex.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension PostWithCompositeKeyAndIndex: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithCompositeKeyAndIndex.IdentifierProtocol { - public static func identifier(id: String, - title: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "title", value: title)]) +public extension PostWithCompositeKeyAndIndex.IdentifierProtocol { + static func identifier( + id: String, + title: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex.swift index 02bf0180d9..f190c30706 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyAndIndex.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithCompositeKeyAndIndex: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional+Schema.swift index 3148b8c002..644cc6a816 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension PostWithCompositeKeyUnidirectional { +public extension PostWithCompositeKeyUnidirectional { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension PostWithCompositeKeyUnidirectional { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let postWithCompositeKeyUnidirectional = PostWithCompositeKeyUnidirectional.keys model.pluralName = "PostWithCompositeKeyUnidirectionals" @@ -35,10 +35,12 @@ extension PostWithCompositeKeyUnidirectional { model.fields( .field(postWithCompositeKeyUnidirectional.id, is: .required, ofType: .string), .field(postWithCompositeKeyUnidirectional.title, is: .required, ofType: .string), - .hasMany(postWithCompositeKeyUnidirectional.comments, - is: .optional, - ofType: CommentWithCompositeKeyUnidirectional.self, - associatedWith: CommentWithCompositeKeyUnidirectional.keys.postWithCompositeKeyUnidirectionalCommentsId), + .hasMany( + postWithCompositeKeyUnidirectional.comments, + is: .optional, + ofType: CommentWithCompositeKeyUnidirectional.self, + associatedWith: CommentWithCompositeKeyUnidirectional.keys.postWithCompositeKeyUnidirectionalCommentsId + ), .field(postWithCompositeKeyUnidirectional.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), .field(postWithCompositeKeyUnidirectional.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) @@ -50,9 +52,11 @@ extension PostWithCompositeKeyUnidirectional: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithCompositeKeyUnidirectional.IdentifierProtocol { - public static func identifier(id: String, - title: String) -> Self { +public extension PostWithCompositeKeyUnidirectional.IdentifierProtocol { + static func identifier( + id: String, + title: String + ) -> Self { .make(fields: [(name: "id", value: id), (name: "title", value: title)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional.swift index 23bffde135..822c27b88e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithCompositeKeyUnidirectional.swift @@ -16,20 +16,26 @@ public struct PostWithCompositeKeyUnidirectional: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey+Schema.swift index 2c0cd997e6..c2d50bd16a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithTagsCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension PostWithTagsCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case tags case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let postWithTagsCompositeKey = PostWithTagsCompositeKey.keys - + model.pluralName = "PostWithTagsCompositeKeys" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [postWithTagsCompositeKey.postId, postWithTagsCompositeKey.title]) ) - + model.fields( .field(postWithTagsCompositeKey.postId, is: .required, ofType: .string), .field(postWithTagsCompositeKey.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension PostWithTagsCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithTagsCompositeKey.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension PostWithTagsCompositeKey.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey.swift index c739bc9c22..73e3e3cd7c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/PostWithTagsCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithTagsCompositeKey: Model { public var tags: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - tags: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + tags: List? = [] + ) { + self.init( + postId: postId, title: title, tags: tags, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - tags: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + tags: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.tags = tags self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2+Schema.swift index 2ca9794b8d..aa67a3738d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Project2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project2 { case project2TeamTeamId case project2TeamName } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let project2 = Project2.keys - + model.pluralName = "Project2s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project2.projectId, project2.name]) ) - + model.fields( .field(project2.projectId, is: .required, ofType: .string), .field(project2.name, is: .required, ofType: .string), @@ -44,9 +51,11 @@ extension Project2: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project2.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project2.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2.swift index 29e0c614bb..3bf27c3b8a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -10,27 +17,33 @@ public struct Project2: Model { public var updatedAt: Temporal.DateTime? public var project2TeamTeamId: String? public var project2TeamName: String? - - public init(projectId: String, - name: String, - team: Team2? = nil, - project2TeamTeamId: String? = nil, - project2TeamName: String? = nil) { - self.init(projectId: projectId, + + public init( + projectId: String, + name: String, + team: Team2? = nil, + project2TeamTeamId: String? = nil, + project2TeamName: String? = nil + ) { + self.init( + projectId: projectId, name: name, team: team, createdAt: nil, updatedAt: nil, project2TeamTeamId: project2TeamTeamId, - project2TeamName: project2TeamName) + project2TeamName: project2TeamName + ) } - internal init(projectId: String, - name: String, - team: Team2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project2TeamTeamId: String? = nil, - project2TeamName: String? = nil) { + init( + projectId: String, + name: String, + team: Team2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project2TeamTeamId: String? = nil, + project2TeamName: String? = nil + ) { self.projectId = projectId self.name = name self.team = team @@ -39,4 +52,4 @@ public struct Project2: Model { self.project2TeamTeamId = project2TeamTeamId self.project2TeamName = project2TeamName } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6+Schema.swift index 6cda02ed54..cda9e71951 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Project6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project6 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let project6 = Project6.keys - + model.pluralName = "Project6s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project6.projectId, project6.name]) ) - + model.fields( .field(project6.projectId, is: .required, ofType: .string), .field(project6.name, is: .required, ofType: .string), @@ -44,9 +51,11 @@ extension Project6: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project6.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project6.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6.swift index 346cb44d71..a7a386cbbf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Project6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -10,27 +17,33 @@ public struct Project6: Model { public var teamName: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(projectId: String, - name: String, - team: Team6? = nil, - teamId: String? = nil, - teamName: String? = nil) { - self.init(projectId: projectId, + + public init( + projectId: String, + name: String, + team: Team6? = nil, + teamId: String? = nil, + teamName: String? = nil + ) { + self.init( + projectId: projectId, name: name, team: team, teamId: teamId, teamName: teamName, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(projectId: String, - name: String, - team: Team6? = nil, - teamId: String? = nil, - teamName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + projectId: String, + name: String, + team: Team6? = nil, + teamId: String? = nil, + teamName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.projectId = projectId self.name = name self.team = team @@ -39,4 +52,4 @@ public struct Project6: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey+Schema.swift index dd535f584d..9332ae93d1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension TagWithCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension TagWithCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case posts case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let tagWithCompositeKey = TagWithCompositeKey.keys - + model.pluralName = "TagWithCompositeKeys" - + model.attributes( .index(fields: ["id", "name"], name: nil), .primaryKey(fields: [tagWithCompositeKey.id, tagWithCompositeKey.name]) ) - + model.fields( .field(tagWithCompositeKey.id, is: .required, ofType: .string), .field(tagWithCompositeKey.name, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension TagWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension TagWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - name: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "name", value: name)]) +public extension TagWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + name: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey.swift index 8d8bbf9f26..b913c944db 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/TagWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct TagWithCompositeKey: Model { public var posts: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2+Schema.swift index 0f7353c4ab..cfe5a5dcfa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case teamId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team2 = Team2.keys - + model.pluralName = "Team2s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team2.teamId, team2.name]) ) - + model.fields( .field(team2.teamId, is: .required, ofType: .string), .field(team2.name, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Team2: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team2.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team2.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2.swift index 90d68caa79..f58e821d6e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Team2: Model { public let name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String) { - self.init(teamId: teamId, + + public init( + teamId: String, + name: String + ) { + self.init( + teamId: teamId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6+Schema.swift index 8556fdcbe1..c212b3c3e8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case teamId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team6 = Team6.keys - + model.pluralName = "Team6s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team6.teamId, team6.name]) ) - + model.fields( .field(team6.teamId, is: .required, ofType: .string), .field(team6.name, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Team6: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team6.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team6.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6.swift index 88da92235b..3a45fc3f04 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/Models/Team6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Team6: Model { public let name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String) { - self.init(teamId: teamId, + + public init( + teamId: String, + name: String + ) { + self.init( + teamId: teamId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/AWSDataStorePrimaryKeyPostComment4V2Test.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/AWSDataStorePrimaryKeyPostComment4V2Test.swift index 5e3d36095c..033add6cc8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/AWSDataStorePrimaryKeyPostComment4V2Test.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/AWSDataStorePrimaryKeyPostComment4V2Test.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import XCTest -import Amplify /* ## iOS 10. bi-directional has-many PostComment4V2 @@ -44,10 +44,10 @@ final class AWSDataStorePrimaryKeyPostComment4V2Test: AWSDataStorePrimaryKeyBase setup(withModels: PostComment4V2()) try await assertDataStoreReady() try await assertQuerySuccess(modelType: Post4V2.self) - + let parent = Post4V2(title: "title") let child = Comment4V2(content: "content", post: parent) - + // Mutations try await assertMutationsParentChild(parent: parent, child: child) } @@ -67,13 +67,13 @@ final class AWSDataStorePrimaryKeyPostComment4V2Test: AWSDataStorePrimaryKeyBase func testSavePostAndLazyLoadComments() async throws { setup(withModels: PostComment4V2()) try await assertDataStoreReady() - + let parent = Post4V2(title: "title") let child = Comment4V2(content: "content", post: parent) - + // Mutations try await assertMutationsParentChild(parent: parent, child: child, shouldDeleteParent: false) - + guard let queriedPost = try await Amplify.DataStore.query(Post4V2.self, byId: parent.id) else { XCTFail("Failed to query post") return @@ -84,7 +84,7 @@ final class AWSDataStorePrimaryKeyPostComment4V2Test: AWSDataStorePrimaryKeyBase } try await comments.fetch() XCTAssertEqual(comments.count, 1) - + try await assertDeleteMutation(parent: parent, child: child) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2+Schema.swift index 600509e366..9e7d8246f4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment4V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment4V2 = Comment4V2.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Comment4V2s" - + model.attributes( .index(fields: ["postID", "content"], name: "byPost4"), .primaryKey(fields: [comment4V2.id]) ) - + model.fields( .field(comment4V2.id, is: .required, ofType: .string), .field(comment4V2.content, is: .required, ofType: .string), @@ -42,4 +49,4 @@ extension Comment4V2 { extension Comment4V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2.swift index 3de4f5acfa..0d4073d6b4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Comment4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Comment4V2: Model { public var post: Post4V2? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2+Schema.swift index e8868bdb5d..dad03d65b6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post4V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post4V2 = Post4V2.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Post4V2s" - + model.attributes( .primaryKey(fields: [post4V2.id]) ) - + model.fields( .field(post4V2.id, is: .required, ofType: .string), .field(post4V2.title, is: .required, ofType: .string), @@ -41,4 +48,4 @@ extension Post4V2 { extension Post4V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2.swift index 08f3e4b429..9106744759 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/10/Post4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4V2: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/AWSDataStoreIntSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/AWSDataStoreIntSortKeyTest.swift index 937ec840b0..fb800973f8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/AWSDataStoreIntSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/AWSDataStoreIntSortKeyTest.swift @@ -12,18 +12,18 @@ type Post11 @model { } */ -import Foundation -import Combine -import XCTest import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import Foundation +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post11.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11+Schema.swift index d051df3340..90282ad891 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post11 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post11 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post11 = Post11.keys - + model.pluralName = "Post11s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post11.postId, post11.sk]) ) - + model.fields( .field(post11.postId, is: .required, ofType: .string), .field(post11.sk, is: .required, ofType: .int), @@ -38,9 +45,11 @@ extension Post11: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post11.IdentifierProtocol { - public static func identifier(postId: String, - sk: Int) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post11.IdentifierProtocol { + static func identifier( + postId: String, + sk: Int + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11.swift index 4fb976c3b9..74ceea138b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/11/Post11.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post11: Model { public let sk: Int public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Int) { - self.init(postId: postId, + + public init( + postId: String, + sk: Int + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Int, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Int, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/AWSDataStoreFloatSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/AWSDataStoreFloatSortKeyTest.swift index 2f9fe125f7..f2d48a7918 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/AWSDataStoreFloatSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/AWSDataStoreFloatSortKeyTest.swift @@ -12,18 +12,18 @@ type Post12 @model { } */ -import Foundation -import Combine -import XCTest import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import Foundation +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post12.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12+Schema.swift index f1dd5b2f65..21cafc2922 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post12 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post12 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post12 = Post12.keys - + model.pluralName = "Post12s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post12.postId, post12.sk]) ) - + model.fields( .field(post12.postId, is: .required, ofType: .string), .field(post12.sk, is: .required, ofType: .double), @@ -38,9 +45,11 @@ extension Post12: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post12.IdentifierProtocol { - public static func identifier(postId: String, - sk: Double) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post12.IdentifierProtocol { + static func identifier( + postId: String, + sk: Double + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12.swift index 672a3f78fc..b9b5b7befb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/12/Post12.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post12: Model { public let sk: Double public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Double) { - self.init(postId: postId, + + public init( + postId: String, + sk: Double + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Double, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Double, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/AWSDataStoreDateTimeSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/AWSDataStoreDateTimeSortKeyTest.swift index 3d3e3704c9..d5612393d8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/AWSDataStoreDateTimeSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/AWSDataStoreDateTimeSortKeyTest.swift @@ -12,18 +12,18 @@ type Post13 @model { } */ -import Foundation -import Combine -import XCTest import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import Foundation +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post13.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13+Schema.swift index 157a720fd9..6f0ba94836 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post13 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post13 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post13 = Post13.keys - + model.pluralName = "Post13s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post13.postId, post13.sk]) ) - + model.fields( .field(post13.postId, is: .required, ofType: .string), .field(post13.sk, is: .required, ofType: .dateTime), @@ -38,9 +45,11 @@ extension Post13: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post13.IdentifierProtocol { - public static func identifier(postId: String, - sk: Temporal.DateTime) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post13.IdentifierProtocol { + static func identifier( + postId: String, + sk: Temporal.DateTime + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13.swift index b889d0582d..9057b054fb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/13/Post13.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post13: Model { public let sk: Temporal.DateTime public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Temporal.DateTime) { - self.init(postId: postId, + + public init( + postId: String, + sk: Temporal.DateTime + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Temporal.DateTime, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Temporal.DateTime, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/AWSDataStoreDateSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/AWSDataStoreDateSortKeyTest.swift index 61303670f0..0e66cce839 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/AWSDataStoreDateSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/AWSDataStoreDateSortKeyTest.swift @@ -12,18 +12,18 @@ type Post14 @model { } */ -import Foundation -import Combine -import XCTest import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import Foundation +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post14.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14+Schema.swift index f77f16fbf1..133032447d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post14 = Post14.keys - + model.pluralName = "Post14s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post14.postId, post14.sk]) ) - + model.fields( .field(post14.postId, is: .required, ofType: .string), .field(post14.sk, is: .required, ofType: .date), @@ -38,9 +45,11 @@ extension Post14: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post14.IdentifierProtocol { - public static func identifier(postId: String, - sk: Temporal.Date) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post14.IdentifierProtocol { + static func identifier( + postId: String, + sk: Temporal.Date + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14.swift index 85c25dad48..f9215fcbf7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/14/Post14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post14: Model { public let sk: Temporal.Date public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Temporal.Date) { - self.init(postId: postId, + + public init( + postId: String, + sk: Temporal.Date + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Temporal.Date, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Temporal.Date, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/AWSDataStoreTimeSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/AWSDataStoreTimeSortKeyTest.swift index 54cf724cee..a028d35f06 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/AWSDataStoreTimeSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/AWSDataStoreTimeSortKeyTest.swift @@ -12,18 +12,18 @@ type Post15 @model { } */ -import Foundation -import Combine -import XCTest import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import Foundation +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post15.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15+Schema.swift index 03789c2f36..b20e0c903c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post15 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post15 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post15 = Post15.keys - + model.pluralName = "Post15s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post15.postId, post15.sk]) ) - + model.fields( .field(post15.postId, is: .required, ofType: .string), .field(post15.sk, is: .required, ofType: .time), @@ -38,9 +45,11 @@ extension Post15: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post15.IdentifierProtocol { - public static func identifier(postId: String, - sk: Temporal.Time) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post15.IdentifierProtocol { + static func identifier( + postId: String, + sk: Temporal.Time + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15.swift index d4b1d8639c..33d9fc2da2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/15/Post15.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post15: Model { public let sk: Temporal.Time public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Temporal.Time) { - self.init(postId: postId, + + public init( + postId: String, + sk: Temporal.Time + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Temporal.Time, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Temporal.Time, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/AWSDataStoreAWSURLSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/AWSDataStoreAWSURLSortKeyTest.swift index 36bc5288fa..e7785430f2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/AWSDataStoreAWSURLSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/AWSDataStoreAWSURLSortKeyTest.swift @@ -13,12 +13,12 @@ type Post16 @model { */ -import Foundation import Combine +import Foundation import XCTest @testable import Amplify -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post16.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16+Schema.swift index 1831e017d4..f4d42c8d04 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post16 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post16 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post16 = Post16.keys - + model.pluralName = "Post16s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post16.postId, post16.sk]) ) - + model.fields( .field(post16.postId, is: .required, ofType: .string), .field(post16.sk, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Post16: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post16.IdentifierProtocol { - public static func identifier(postId: String, - sk: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post16.IdentifierProtocol { + static func identifier( + postId: String, + sk: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16.swift index b7fc048f3b..6adcd658b0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/16/Post16.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post16: Model { public let sk: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: String) { - self.init(postId: postId, + + public init( + postId: String, + sk: String + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/AWSDataStoreAWSEmailSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/AWSDataStoreAWSEmailSortKeyTest.swift index fb1a1e78c6..53b650e780 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/AWSDataStoreAWSEmailSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/AWSDataStoreAWSEmailSortKeyTest.swift @@ -13,12 +13,12 @@ type Post17 @model { */ -import Foundation import Combine +import Foundation import XCTest @testable import Amplify -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post17.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17+Schema.swift index 73d0919c9b..226608e21a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post17 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post17 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post17 = Post17.keys - + model.pluralName = "Post17s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post17.postId, post17.sk]) ) - + model.fields( .field(post17.postId, is: .required, ofType: .string), .field(post17.sk, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Post17: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post17.IdentifierProtocol { - public static func identifier(postId: String, - sk: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post17.IdentifierProtocol { + static func identifier( + postId: String, + sk: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17.swift index 269fb145f1..cbe271bf43 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/17/Post17.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post17: Model { public let sk: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: String) { - self.init(postId: postId, + + public init( + postId: String, + sk: String + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/AWSDataStoreAWSPhoneSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/AWSDataStoreAWSPhoneSortKeyTest.swift index 895ac21f0e..33b422b510 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/AWSDataStoreAWSPhoneSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/AWSDataStoreAWSPhoneSortKeyTest.swift @@ -13,12 +13,12 @@ type Post18 @model { */ -import Foundation import Combine +import Foundation import XCTest @testable import Amplify -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post18.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18+Schema.swift index 2e55573dff..4b72dbfb87 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post18 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post18 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post18 = Post18.keys - + model.pluralName = "Post18s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post18.postId, post18.sk]) ) - + model.fields( .field(post18.postId, is: .required, ofType: .string), .field(post18.sk, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Post18: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post18.IdentifierProtocol { - public static func identifier(postId: String, - sk: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post18.IdentifierProtocol { + static func identifier( + postId: String, + sk: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18.swift index c83ab5b693..5c42bdc6cf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/18/Post18.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post18: Model { public let sk: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: String) { - self.init(postId: postId, + + public init( + postId: String, + sk: String + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/AWSDataStoreAWSIPAddressSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/AWSDataStoreAWSIPAddressSortKeyTest.swift index 12504a06c6..065042f783 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/AWSDataStoreAWSIPAddressSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/AWSDataStoreAWSIPAddressSortKeyTest.swift @@ -13,12 +13,12 @@ type Post19 @model { */ -import Foundation import Combine +import Foundation import XCTest @testable import Amplify -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post19.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19+Schema.swift index b1ab4b2583..29d76f98f3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post19 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post19 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post19 = Post19.keys - + model.pluralName = "Post19s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post19.postId, post19.sk]) ) - + model.fields( .field(post19.postId, is: .required, ofType: .string), .field(post19.sk, is: .required, ofType: .string), @@ -38,9 +45,11 @@ extension Post19: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post19.IdentifierProtocol { - public static func identifier(postId: String, - sk: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post19.IdentifierProtocol { + static func identifier( + postId: String, + sk: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19.swift index 8b7790fcfb..5c241b8554 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/19/Post19.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post19: Model { public let sk: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: String) { - self.init(postId: postId, + + public init( + postId: String, + sk: String + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/AWSDataStoreAWSTimestampSortKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/AWSDataStoreAWSTimestampSortKeyTest.swift index 0fc64bcfb8..12e981f542 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/AWSDataStoreAWSTimestampSortKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/AWSDataStoreAWSTimestampSortKeyTest.swift @@ -13,12 +13,12 @@ type Post20 @model { */ -import Foundation import Combine +import Foundation import XCTest @testable import Amplify -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post20.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20+Schema.swift index e6085a7f89..9f6bb3cfe5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post20 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post20 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case sk case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post20 = Post20.keys - + model.pluralName = "Post20s" - + model.attributes( .index(fields: ["postId", "sk"], name: nil), .primaryKey(fields: [post20.postId, post20.sk]) ) - + model.fields( .field(post20.postId, is: .required, ofType: .string), .field(post20.sk, is: .required, ofType: .int), @@ -38,9 +45,11 @@ extension Post20: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post20.IdentifierProtocol { - public static func identifier(postId: String, - sk: Int) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "sk", value: sk)]) +public extension Post20.IdentifierProtocol { + static func identifier( + postId: String, + sk: Int + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "sk", value: sk)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20.swift index 283f641af2..e1eb3e5b98 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/20/Post20.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Post20: Model { public let sk: Int public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - sk: Int) { - self.init(postId: postId, + + public init( + postId: String, + sk: Int + ) { + self.init( + postId: postId, sk: sk, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - sk: Int, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + sk: Int, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.sk = sk self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/AWSDataStorePrimaryKeyPostCommentCompositeKeyTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/AWSDataStorePrimaryKeyPostCommentCompositeKeyTest.swift index 3ecaa6d733..1972003a89 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/AWSDataStorePrimaryKeyPostCommentCompositeKeyTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/AWSDataStorePrimaryKeyPostCommentCompositeKeyTest.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - +import Amplify import Foundation import XCTest -import Amplify /* # iOS.7. A Has-Many/Belongs-To relationship, each with a composite key @@ -35,15 +34,17 @@ final class AWSDataStorePrimaryKeyPostCommentCompositeKeyTest: AWSDataStorePrima try await assertQuerySuccess(modelType: PostWithCompositeKey.self) let parent = PostWithCompositeKey(title: "Post22") let child = CommentWithCompositeKey(content: "Comment", post: parent) - + // Mutations try await assertMutationsParentChild(parent: parent, child: child) // Child should not exists as we've deleted the parent - try await assertModelDeleted(modelType: CommentWithCompositeKey.self, - identifier: .identifier(id: child.id, content: child.content)) + try await assertModelDeleted( + modelType: CommentWithCompositeKey.self, + identifier: .identifier(id: child.id, content: child.content) + ) } - + /// - Given: a set models with a belongs-to association and composite primary keys /// - When: /// - the parent model is saved @@ -55,7 +56,7 @@ final class AWSDataStorePrimaryKeyPostCommentCompositeKeyTest: AWSDataStorePrima setup(withModels: CompositeKeyWithAssociations()) try await assertDataStoreReady() - + let post = PostWithCompositeKey(title: "title") let comment = CommentWithCompositeKey(content: "content", post: post) _ = try await Amplify.DataStore.save(post) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey+Schema.swift index e267c86f93..669e370130 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CommentWithCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension CommentWithCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let commentWithCompositeKey = CommentWithCompositeKey.keys - + model.pluralName = "CommentWithCompositeKeys" - + model.attributes( .index(fields: ["id", "content"], name: nil), .primaryKey(fields: [commentWithCompositeKey.id, commentWithCompositeKey.content]) ) - + model.fields( .field(commentWithCompositeKey.id, is: .required, ofType: .string), .field(commentWithCompositeKey.content, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension CommentWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CommentWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - content: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "content", value: content)]) +public extension CommentWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + content: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "content", value: content)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey.swift index ab7db0012a..e634f7e71a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/CommentWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct CommentWithCompositeKey: Model { public var post: PostWithCompositeKey? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey+Schema.swift index e7a9c5e1f4..ee14b480cc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithCompositeKey { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension PostWithCompositeKey { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let postWithCompositeKey = PostWithCompositeKey.keys - + model.pluralName = "PostWithCompositeKeys" - + model.attributes( .index(fields: ["id", "title"], name: nil), .primaryKey(fields: [postWithCompositeKey.id, postWithCompositeKey.title]) ) - + model.fields( .field(postWithCompositeKey.id, is: .required, ofType: .string), .field(postWithCompositeKey.title, is: .required, ofType: .string), @@ -40,9 +47,11 @@ extension PostWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - title: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "title", value: title)]) +public extension PostWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + title: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "title", value: title)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey.swift index e9de7de986..ac441cae5d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/7/PostWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithCompositeKey: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/AWSDataStoreCompositeSortKeyIdentifierTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/AWSDataStoreCompositeSortKeyIdentifierTest.swift index f107bc47bf..644b19e428 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/AWSDataStoreCompositeSortKeyIdentifierTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/AWSDataStoreCompositeSortKeyIdentifierTest.swift @@ -5,18 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // - -import XCTest -import Combine import AWSAPIPlugin import AWSDataStorePlugin +import Combine +import XCTest @testable import Amplify #if !os(watchOS) @testable import DataStoreHostApp #endif -fileprivate struct TestModels: AmplifyModelRegistration { +private struct TestModels: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post9.self) ModelRegistry.register(modelType: Comment9.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9+Schema.swift index 3833a860c3..3a55bfcf85 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment9 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment9 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case postId case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment9 = Comment9.keys - + model.pluralName = "Comment9s" - + model.attributes( .index(fields: ["commentId", "postId"], name: nil), .index(fields: ["postId"], name: "byPost9"), .primaryKey(fields: [comment9.commentId, comment9.postId]) ) - + model.fields( .field(comment9.commentId, is: .required, ofType: .string), .field(comment9.postId, is: .required, ofType: .string), @@ -41,9 +48,11 @@ extension Comment9: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment9.IdentifierProtocol { - public static func identifier(commentId: String, - postId: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "postId", value: postId)]) +public extension Comment9.IdentifierProtocol { + static func identifier( + commentId: String, + postId: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "postId", value: postId)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9.swift index 8082abb929..b967bd4c0c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Comment9.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Comment9: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - postId: String, - content: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + postId: String, + content: String? = nil + ) { + self.init( + commentId: commentId, postId: postId, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(commentId: String, - postId: String, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + postId: String, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.postId = postId self.content = content self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9+Schema.swift index 4bf0b0c40c..dc75b370dd 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post9 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post9 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post9 = Post9.keys - + model.pluralName = "Post9s" - + model.attributes( .index(fields: ["postId"], name: nil), .primaryKey(fields: [post9.postId]) ) - + model.fields( .field(post9.postId, is: .required, ofType: .string), .field(post9.title, is: .optional, ofType: .string), @@ -40,8 +47,8 @@ extension Post9: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post9.IdentifierProtocol { - public static func identifier(postId: String) -> Self { - .make(fields:[(name: "postId", value: postId)]) +public extension Post9.IdentifierProtocol { + static func identifier(postId: String) -> Self { + .make(fields: [(name: "postId", value: postId)]) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9.swift index ac8e74970b..1da58b19c6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/9/Post9.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post9: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String? = nil, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String? = nil, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift index 6f22c32ed0..23087ef545 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSAPIPlugin +import AWSDataStorePlugin +import Combine import Foundation import XCTest -import Combine -import AWSDataStorePlugin -import AWSAPIPlugin #if !os(watchOS) @testable import DataStoreHostApp #endif @@ -79,7 +79,7 @@ extension AWSDataStorePrimaryKeyBaseTest { /// - modelType: model type /// - expectation: success XCTestExpectation /// - onFailure: on failure callback - func assertQuerySuccess(modelType: M.Type) async throws { + func assertQuerySuccess(modelType: (some Model).Type) async throws { let models = try await Amplify.DataStore.query(modelType) XCTAssertNotNil(models) } @@ -89,8 +89,10 @@ extension AWSDataStorePrimaryKeyBaseTest { /// - modelType: model type /// - expectation: success XCTestExpectation /// - onFailure: on failure callback - func assertModelDeleted(modelType: M.Type, - identifier: ModelIdentifier) async throws { + func assertModelDeleted( + modelType: M.Type, + identifier: ModelIdentifier + ) async throws { let model = try await Amplify.DataStore.query(modelType, byIdentifier: identifier) XCTAssertNil(model) } @@ -101,7 +103,7 @@ extension AWSDataStorePrimaryKeyBaseTest { let ready = expectation(description: "Ready") let subscriptionsEstablished = expectation(description: "Subscriptions established") let modelsSynced = expectation(description: "Models synced") - + var modelSyncedCount = 0 let dataStoreEvents = HubPayload.EventName.DataStore.self Amplify @@ -143,8 +145,8 @@ extension AWSDataStorePrimaryKeyBaseTest { /// - model: model instance saved and then deleted /// - expectations: test expectations /// - onFailure: failure callback - func assertMutations(model: M) async throws { - + func assertMutations(model: some Model & ModelIdentifiable) async throws { + let mutationSaveProcessed = expectation(description: "mutation save processed") Amplify .Hub @@ -152,7 +154,8 @@ extension AWSDataStorePrimaryKeyBaseTest { .filter { $0.eventName == HubPayload.EventName.DataStore.syncReceived } .sink { payload in guard let mutationEvent = payload.data as? MutationEvent, - mutationEvent.modelId == model.identifier else { + mutationEvent.modelId == model.identifier + else { return } @@ -177,7 +180,8 @@ extension AWSDataStorePrimaryKeyBaseTest { .filter { $0.eventName == HubPayload.EventName.DataStore.syncReceived } .sink { payload in guard let mutationEvent = payload.data as? MutationEvent, - mutationEvent.modelId == model.identifier else { + mutationEvent.modelId == model.identifier + else { return } @@ -187,7 +191,7 @@ extension AWSDataStorePrimaryKeyBaseTest { } } .store(in: &requests) - + try await Amplify.DataStore.delete(model) await fulfillment( of: [mutationDeleteProcessed], @@ -200,20 +204,22 @@ extension AWSDataStorePrimaryKeyBaseTest { /// - model: model instance saved and then deleted /// - expectations: test expectations /// - onFailure: failure callback - func assertMutationsParentChild(parent: P, - child: C, - shouldDeleteParent: Bool = true) async throws { + func assertMutationsParentChild( + parent: some Model & ModelIdentifiable, + child: some Model & ModelIdentifiable, + shouldDeleteParent: Bool = true + ) async throws { let mutationSaveProcessed = expectation(description: "mutation saved processed") mutationSaveProcessed.expectedFulfillmentCount = 2 - + Amplify .Hub .publisher(for: .dataStore) .filter { $0.eventName == HubPayload.EventName.DataStore.syncReceived } .sink { payload in guard let mutationEvent = payload.data as? MutationEvent, - mutationEvent.modelId == parent.identifier || mutationEvent.modelId == child.identifier else { + mutationEvent.modelId == parent.identifier || mutationEvent.modelId == child.identifier + else { return } @@ -226,7 +232,7 @@ extension AWSDataStorePrimaryKeyBaseTest { // save parent first _ = try await Amplify.DataStore.save(parent) - + // save child _ = try await Amplify.DataStore.save(child) @@ -235,12 +241,11 @@ extension AWSDataStorePrimaryKeyBaseTest { guard shouldDeleteParent else { return } - + try await assertDeleteMutation(parent: parent, child: child) } - - func assertDeleteMutation(parent: P, child: C) async throws { + + func assertDeleteMutation(parent: some Model & ModelIdentifiable, child: some Model & ModelIdentifiable) async throws { let mutationDeleteProcessed = expectation(description: "mutation delete processed") Amplify .Hub @@ -248,7 +253,8 @@ extension AWSDataStorePrimaryKeyBaseTest { .filter { $0.eventName == HubPayload.EventName.DataStore.syncReceived } .sink { payload in guard let mutationEvent = payload.data as? MutationEvent, - mutationEvent.modelId == parent.identifier || mutationEvent.modelId == child.identifier else { + mutationEvent.modelId == parent.identifier || mutationEvent.modelId == child.identifier + else { return } @@ -258,7 +264,7 @@ extension AWSDataStorePrimaryKeyBaseTest { } } .store(in: &requests) - + // delete parent try await Amplify.DataStore.delete(parent) await fulfillment(of: [mutationDeleteProcessed], timeout: 60) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyTests.swift index 6e367f892d..44b67a0a41 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import XCTest -import Amplify class AWSDataStorePrimaryKeyIntegrationTests: AWSDataStorePrimaryKeyBaseTest { @@ -88,5 +88,5 @@ extension AWSDataStorePrimaryKeyIntegrationTests { } } - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStoreSortKeyBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStoreSortKeyBaseTest.swift index 1eeb5518ea..63cfc4c38c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStoreSortKeyBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStoreSortKeyBaseTest.swift @@ -5,9 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Combine +import Foundation import XCTest import AWSAPIPlugin diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/AWSDataStoreCategoryPluginFlutterIntegrationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/AWSDataStoreCategoryPluginFlutterIntegrationTests.swift index 8ed02462c9..9d56615fe8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/AWSDataStoreCategoryPluginFlutterIntegrationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/AWSDataStoreCategoryPluginFlutterIntegrationTests.swift @@ -4,9 +4,10 @@ // // SPDX-License-Identifier: Apache-2.0 // -import XCTest + import Amplify import AWSDataStorePlugin +import XCTest class AWSDataStorePluginFlutterConfigurationTests: XCTestCase { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario1FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario1FlutterTests.swift index de1c6d6309..8a4fc2aaa4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario1FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario1FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -34,8 +35,10 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest let project = try Project1Wrapper(team: team.model) let syncedTeamReceived = expectation(description: "received team from sync path") let syncProjectReceived = expectation(description: "received project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -103,8 +106,10 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest let expectedUpdatedProject = project.copy() as! Project1Wrapper try expectedUpdatedProject.setTeam(team: anotherTeam.model) let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -182,7 +187,8 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name"), - let project = try saveProject(team: team) else { + let project = try saveProject(team: team) + else { XCTFail("Could not save team and project") return } @@ -213,7 +219,8 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name"), - let project = try saveProject(team: team) else { + let project = try saveProject(team: team) + else { XCTFail("Could not save team and project") return } @@ -240,7 +247,7 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest let queriedProjectExpect0 = queryProject(id: project.model.id) XCTAssertNotNil(queriedProjectExpect0) XCTAssertEqual(0, queriedProjectExpect0!.count) - if queriedProjectExpect0!.count == 0 { + if queriedProjectExpect0!.isEmpty { getProjectAfterDeleteCompleted.fulfill() } await fulfillment(of: [getProjectAfterDeleteCompleted], timeout: TestCommonConstants.networkTimeout) @@ -250,7 +257,8 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name"), - let project = try saveProject(team: team) else { + let project = try saveProject(team: team) + else { XCTFail("Could not save team and project") return } @@ -334,8 +342,10 @@ class DataStoreConnectionScenario1FlutterTests: SyncEngineFlutterIntegrationTest return TeamWrapper(model: result!) } - func saveProject(name: String = "project", - team: TeamWrapper) throws -> Project1Wrapper? { + func saveProject( + name: String = "project", + team: TeamWrapper + ) throws -> Project1Wrapper? { let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin let project = try Project1Wrapper(name: name, team: team.model) var result: FlutterSerializedModel? diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario2FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario2FlutterTests.swift index 36d7684b18..25a02a7b42 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario2FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario2FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -36,8 +37,10 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest let project = try Project2Wrapper(name: "project1", team: team.model, teamID: team.idString()) let syncedTeamReceived = expectation(description: "received team from sync event") let syncProjectReceived = expectation(description: "received project from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -98,8 +101,10 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest try expectedUpdatedProject.setTeam(name: "project1", team: anotherTeam.model, teamID: anotherTeam.idString()) let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -179,7 +184,8 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name", plugin: plugin), - let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) else { + let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) + else { XCTFail("Could not save team and project") return @@ -240,7 +246,8 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name", plugin: plugin), - let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) else { + let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) + else { XCTFail("Could not save team and project") return } @@ -275,7 +282,8 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let team = try saveTeam(name: "name", plugin: plugin), - let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) else { + let project = try saveProject(teamID: team.idString(), team: team, plugin: plugin) + else { XCTFail("Could not save team and project") return } @@ -358,9 +366,11 @@ class DataStoreConnectionScenario2FlutterTests: SyncEngineFlutterIntegrationTest return result } - func saveProject(teamID: String, - team: TeamWrapper, - plugin: AWSDataStorePlugin) throws -> Project2Wrapper? { + func saveProject( + teamID: String, + team: TeamWrapper, + plugin: AWSDataStorePlugin + ) throws -> Project2Wrapper? { let project = try Project2Wrapper(name: name, team: team.model, teamID: teamID) var result: Project2Wrapper? let completeInvoked = expectation(description: "request completed") diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario3FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario3FlutterTests.swift index 05a9730c4e..b4f415746c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario3FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario3FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -36,8 +37,10 @@ class DataStoreConnectionScenario3FlutterTests: SyncEngineFlutterIntegrationTest let comment = try Comment3Wrapper(postID: post.idString(), content: "content") let syncedPostReceived = expectation(description: "received post from sync event") let syncCommentReceived = expectation(description: "received comment from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -185,7 +188,8 @@ class DataStoreConnectionScenario3FlutterTests: SyncEngineFlutterIntegrationTest func savePost(id: String = UUID().uuidString, title: String, plugin: AWSDataStorePlugin) throws -> Post3Wrapper? { let post = try Post3Wrapper( id: id, - title: title) + title: title + ) var result: Post3Wrapper? let completeInvoked = expectation(description: "request completed") plugin.save(post.model, modelSchema: Post3.schema) { event in diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario4FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario4FlutterTests.swift index 93afce11cb..6bf7d178f7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario4FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario4FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario5FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario5FlutterTests.swift index 757cbdda17..1a9e695a52 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario5FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario5FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario6FlutterTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario6FlutterTests.swift index 6c9f84111a..9350a39658 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario6FlutterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/Connection/DataStoreConnectionScenario6FlutterTests.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -40,7 +41,8 @@ class DataStoreConnectionScenario6FlutterTests: SyncEngineFlutterIntegrationTest let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin guard let blog = try saveBlog(name: "name", plugin: plugin), let post = try savePost(title: "title", blog: blog, plugin: plugin), - let comment = try saveComment(post: post, content: "content", plugin: plugin) else { + let comment = try saveComment(post: post, content: "content", plugin: plugin) + else { XCTFail("Could not create blog, post, and comment") return } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterConsecutiveUpdatesTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterConsecutiveUpdatesTests.swift index 1aac1aa85e..21181bd63a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterConsecutiveUpdatesTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterConsecutiveUpdatesTests.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import XCTest + import AWSPluginsCore +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -20,8 +21,10 @@ class DataStoreFlutterConsecutiveUpdatesTests: SyncEngineFlutterIntegrationTestB func testSaveAndImmediatelyUpdate() async throws { try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin - let newPost = try PostWrapper(title: "MyPost", - content: "This is my post.") + let newPost = try PostWrapper( + title: "MyPost", + content: "This is my post." + ) let updatedPost = newPost try updatedPost.updateRating(rating: 5) @@ -33,7 +36,8 @@ class DataStoreFlutterConsecutiveUpdatesTests: SyncEngineFlutterIntegrationTestB let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return @@ -135,17 +139,20 @@ class DataStoreFlutterConsecutiveUpdatesTests: SyncEngineFlutterIntegrationTestB func testSaveAndImmediatelyDelete() async throws { try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin - let newPost = try PostWrapper(title: "MyPost", - content: "This is my post.", - createdAt: Temporal.DateTime.now().iso8601String, - rating: 3) + let newPost = try PostWrapper( + title: "MyPost", + content: "This is my post.", + createdAt: Temporal.DateTime.now().iso8601String, + rating: 3 + ) let saveSyncReceived = expectation(description: "Received create mutation event on subscription for Post") let deleteSyncReceived = expectation(description: "Received delete mutation event on subscription for Post") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return @@ -241,10 +248,12 @@ class DataStoreFlutterConsecutiveUpdatesTests: SyncEngineFlutterIntegrationTestB try startAmplifyAndWaitForSync() let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin - let newPost = try PostWrapper(title: "MyPost", - content: "This is my post.", - createdAt: Temporal.DateTime.now().iso8601String, - rating: 3) + let newPost = try PostWrapper( + title: "MyPost", + content: "This is my post.", + createdAt: Temporal.DateTime.now().iso8601String, + rating: 3 + ) var updatedPost = newPost try updatedPost.updateRating(rating: 5) @@ -257,7 +266,8 @@ class DataStoreFlutterConsecutiveUpdatesTests: SyncEngineFlutterIntegrationTestB let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterEndToEndTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterEndToEndTests.swift index ce1a143e1e..81910c8889 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterEndToEndTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/DataStoreFlutterEndToEndTests.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import XCTest + import AWSPluginsCore +import XCTest @testable import Amplify @testable import AmplifyTestCommon @@ -22,12 +23,14 @@ class DataStoreEndToEndTests: SyncEngineFlutterIntegrationTestBase { let newPost = try PostWrapper( title: title, - content: "Original content from DataStoreEndToEndTests at \(date)") + content: "Original content from DataStoreEndToEndTests at \(date)" + ) let updatedPost = try PostWrapper( id: newPost.idString(), title: title, - content: "UPDATED CONTENT from DataStoreEndToEndTests at \(date)") + content: "UPDATED CONTENT from DataStoreEndToEndTests at \(date)" + ) let createReceived = expectation(description: "Create notification received") let updateReceived = expectation(description: "Update notification received") @@ -35,7 +38,8 @@ class DataStoreEndToEndTests: SyncEngineFlutterIntegrationTestBase { let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -102,7 +106,8 @@ class DataStoreEndToEndTests: SyncEngineFlutterIntegrationTestBase { let newPost = try PostWrapper( title: title, content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: date) + createdAt: date + ) let updatedPost = try PostWrapper( id: newPost.idString(), @@ -116,7 +121,8 @@ class DataStoreEndToEndTests: SyncEngineFlutterIntegrationTestBase { let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -259,11 +265,13 @@ class DataStoreEndToEndTests: SyncEngineFlutterIntegrationTestBase { let newPost = try PostWrapper( title: "This is a new post I created", content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: Temporal.DateTime.now().iso8601String) + createdAt: Temporal.DateTime.now().iso8601String + ) let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterDataStoreRequestUtils.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterDataStoreRequestUtils.swift index 14af3a8385..03e3a4d431 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterDataStoreRequestUtils.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterDataStoreRequestUtils.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation public class FlutterDataStoreRequestUtils { @@ -13,8 +14,10 @@ public class FlutterDataStoreRequestUtils { guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonDict) else { throw DataStoreError.decodingError("Unable to deserialize json data", "Check the model structure.") } - guard let jsonValue = try? JSONDecoder().decode(Dictionary.self, - from: jsonData) else { + guard let jsonValue = try? JSONDecoder().decode( + [String: JSONValue].self, + from: jsonData + ) else { throw DataStoreError.decodingError("Unable to decode json value", "Check the model structure.") } return jsonValue diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterSerializedModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterSerializedModel.swift index e0f064c370..ea062d5236 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterSerializedModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterSerializedModel.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation /// `FlutterSerializedModel` assists in serializing and deserializing JSON when interacting with the amplify-ios DataStore API. /// Taken from [amplify-flutter DataStore category](https://github.com/aws-amplify/amplify-flutter/blob/main/packages/amplify_datastore/ios/Classes/types/model/FlutterSerializedModel.swift) @@ -22,7 +23,7 @@ struct FlutterSerializedModel: Model, JSONValueHolder { public init(from decoder: Decoder) throws { let y = try decoder.container(keyedBy: CodingKeys.self) - id = try y.decode(String.self, forKey: .id) + self.id = try y.decode(String.self, forKey: .id) let json = try JSONValue(from: decoder) let typeName = json["__typename"] @@ -30,9 +31,9 @@ struct FlutterSerializedModel: Model, JSONValueHolder { if case .object(var v) = modified { v["__typename"] = typeName - values = v + self.values = v } else { - values = [:] + self.values = [:] } } @@ -147,7 +148,7 @@ struct FlutterSerializedModel: Model, JSONValueHolder { private func generateSerializedData(modelSchema: ModelSchema) -> [String: Any] { var result = [String: Any]() - for(key, value) in values { + for (key, value) in values { let field = modelSchema.field(withName: key) if value == nil { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterTemporal.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterTemporal.swift index 8d852cba5e..fc4485c02e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterTemporal.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/AmplifyFlutterHelpers/FlutterTemporal.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify import Foundation diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Blog6Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Blog6Wrapper.swift index 1b58afcaa3..6a3c252ec5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Blog6Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Blog6Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Blog6 */ class Blog6Wrapper: NSCopying { @@ -21,7 +21,7 @@ class Blog6Wrapper: NSCopying { let map: [String: Any] = [ "name": name ] - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -29,19 +29,19 @@ class Blog6Wrapper: NSCopying { } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func name() -> JSONValue? { - return self.model.values["name"] + return model.values["name"] } func posts() -> JSONValue? { - return self.model.values["posts"] + return model.values["posts"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift index c680e500ed..c3fe37bdf2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Comment3 */ @@ -23,11 +23,11 @@ class Comment3Wrapper: NSCopying { "postID": postID, "content": content ] - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(id: String = UUID().uuidString, content: String, post: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["content": content, "team": post.toMap(modelSchema: Post3.schema)])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["content": content, "team": post.toMap(modelSchema: Post3.schema)])) } init(model: FlutterSerializedModel) { @@ -37,28 +37,28 @@ class Comment3Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func setPostId(postId: String) throws { - self.model.values["postID"] = JSONValue.string(postId) + model.values["postID"] = JSONValue.string(postId) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func content() -> JSONValue? { - return self.model.values["content"] + return model.values["content"] } func postId() -> JSONValue? { - return self.model.values["postID"] + return model.values["postID"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift index ca57fcb2cc..6597a0825d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Comment4 */ class Comment4Wrapper: NSCopying { var model: FlutterSerializedModel init(id: String = UUID().uuidString, content: String, post: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["content": content, "post": post.toMap(modelSchema: Post4.schema)])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["content": content, "post": post.toMap(modelSchema: Post4.schema)])) } init(model: FlutterSerializedModel) { @@ -28,23 +28,23 @@ class Comment4Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func setPost(post: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: self.model.id, map: try FlutterDataStoreRequestUtils.getJSONValue(["content": "content", "post": post.toMap(modelSchema: Post4.schema)])) + model = try FlutterSerializedModel(id: model.id, map: FlutterDataStoreRequestUtils.getJSONValue(["content": "content", "post": post.toMap(modelSchema: Post4.schema)])) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func post() -> JSONValue? { - return self.model.values["post"] + return model.values["post"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment6Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment6Wrapper.swift index a5c0a26f21..7cd87774a4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment6Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment6Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Comment6 */ class Comment6Wrapper: NSCopying { @@ -22,7 +22,7 @@ class Comment6Wrapper: NSCopying { "content": content, "post": post.toMap(modelSchema: Post6.schema) ] - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -30,18 +30,18 @@ class Comment6Wrapper: NSCopying { } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func content() -> JSONValue? { - return self.model.values["content"] + return model.values["content"] } func post() -> JSONValue? { - return self.model.values["post"] + return model.values["post"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift index ad8b6e3c96..e9cfd95bb0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. @@ -27,10 +27,10 @@ class Post3Wrapper: NSCopying { "title": title ] - if serializedComments.count > 0 { + if !serializedComments.isEmpty { map["comments"] = serializedComments } - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -40,19 +40,19 @@ class Post3Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func title() -> JSONValue? { - return self.model.values["title"] + return model.values["title"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift index a9ae659d5c..86cffa5a8e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Post4 */ class Post4Wrapper: NSCopying { @@ -28,10 +28,10 @@ class Post4Wrapper: NSCopying { "title": title ] - if serializedComments.count > 0 { + if !serializedComments.isEmpty { map["comments"] = serializedComments } - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -41,19 +41,19 @@ class Post4Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func title() -> JSONValue? { - return self.model.values["title"] + return model.values["title"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift index 44b3d51016..fa9b1afd43 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Post5 */ class Post5Wrapper: NSCopying { @@ -21,7 +21,7 @@ class Post5Wrapper: NSCopying { let map: [String: Any] = [ "title": title ] - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -31,23 +31,23 @@ class Post5Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func title() -> JSONValue? { - return self.model.values["title"] + return model.values["title"] } func editors() -> JSONValue? { - return self.model.values["editors"] + return model.values["editors"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift index 1a9951d7fe..42730f10f6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Post6 */ class Post6Wrapper: NSCopying { @@ -22,7 +22,7 @@ class Post6Wrapper: NSCopying { "title": title, "blog": blog.toMap(modelSchema: Blog6.schema) ] - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -32,23 +32,23 @@ class Post6Wrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func title() -> JSONValue? { - return self.model.values["title"] + return model.values["title"] } func blog() -> JSONValue? { - return self.model.values["blog"] + return model.values["blog"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostEditor5Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostEditor5Wrapper.swift index 00155aa33f..d070e93e98 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostEditor5Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostEditor5Wrapper.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: PostEditor5 */ class PostEditor5Wrapper: NSCopying { var model: FlutterSerializedModel init(post: FlutterSerializedModel, editor: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["post": post.toMap(modelSchema: Post5.schema), "editor": editor.toMap(modelSchema: User5.schema)])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["post": post.toMap(modelSchema: Post5.schema), "editor": editor.toMap(modelSchema: User5.schema)])) } init(model: FlutterSerializedModel) { @@ -26,11 +26,11 @@ class PostEditor5Wrapper: NSCopying { } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift index b2a447858f..0bb22649f8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Post */ class PostWrapper: NSCopying { @@ -24,7 +24,7 @@ class PostWrapper: NSCopying { "createdAt": createdAt, "rating": rating ] - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } init(model: FlutterSerializedModel) { @@ -34,7 +34,7 @@ class PostWrapper: NSCopying { init(json: String) throws { let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] - self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) + self.model = try FlutterSerializedModel(id: map!["id"] as! String, map: FlutterDataStoreRequestUtils.getJSONValue(map!)) } init(post: Post) throws { @@ -44,43 +44,43 @@ class PostWrapper: NSCopying { "createdAt": post.createdAt.iso8601String, "rating": post.rating ] - self.model = FlutterSerializedModel(id: post.id, map: try FlutterDataStoreRequestUtils.getJSONValue(map)) + self.model = try FlutterSerializedModel(id: post.id, map: FlutterDataStoreRequestUtils.getJSONValue(map)) } func updateRating(rating: Double) throws { - var map = self.model.values + var map = model.values map["rating"] = JSONValue.init(floatLiteral: rating) - self.model = FlutterSerializedModel(id: self.model.id, map: map) + model = FlutterSerializedModel(id: model.id, map: map) } func updateStringProp(key: String, value: String) throws { - var map = self.model.values + var map = model.values map[key] = JSONValue.string(value) - self.model = FlutterSerializedModel(id: self.model.id, map: map) + model = FlutterSerializedModel(id: model.id, map: map) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func title() -> JSONValue? { - return self.model.values["title"] + return model.values["title"] } func rating() -> JSONValue? { - return self.model.values["rating"] + return model.values["rating"] } func content() -> JSONValue? { - return self.model.values["content"] + return model.values["content"] } func createdAt() -> JSONValue? { - return self.model.values["createdAt"] + return model.values["createdAt"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project1Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project1Wrapper.swift index c01e59f9a8..112d7d5df2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project1Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project1Wrapper.swift @@ -5,24 +5,24 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Project1 */ class Project1Wrapper: NSCopying { var model: FlutterSerializedModel init(team: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["team": team.toMap(modelSchema: Team1.schema)])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["team": team.toMap(modelSchema: Team1.schema)])) } init(name: String, team: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team1.schema)])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team1.schema)])) } init(model: FlutterSerializedModel) { @@ -30,23 +30,23 @@ class Project1Wrapper: NSCopying { } func setTeam(team: FlutterSerializedModel) throws { - self.model = FlutterSerializedModel(id: self.model.id, map: try FlutterDataStoreRequestUtils.getJSONValue(["team": team.toMap(modelSchema: Team1.schema)])) + model = try FlutterSerializedModel(id: model.id, map: FlutterDataStoreRequestUtils.getJSONValue(["team": team.toMap(modelSchema: Team1.schema)])) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func teamId() -> JSONValue? { - return self.model.values["team"]!["id"] + return model.values["team"]!["id"] } func teamName() -> JSONValue? { - return self.model.values["team"]!["name"] + return model.values["team"]!["name"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project2Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project2Wrapper.swift index a5f11f0928..5ee758da52 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project2Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Project2Wrapper.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Project2 */ class Project2Wrapper: NSCopying { var model: FlutterSerializedModel init(name: String, team: FlutterSerializedModel, teamID: String) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team2.schema), "teamID": teamID])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team2.schema), "teamID": teamID])) } init(model: FlutterSerializedModel) { @@ -26,23 +26,23 @@ class Project2Wrapper: NSCopying { } func setTeam(name: String, team: FlutterSerializedModel, teamID: String) throws { - self.model = FlutterSerializedModel(id: self.model.id, map: try FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team2.schema), "teamID": teamID])) + model = try FlutterSerializedModel(id: model.id, map: FlutterDataStoreRequestUtils.getJSONValue(["name": name, "team": team.toMap(modelSchema: Team2.schema), "teamID": teamID])) } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func teamID() -> JSONValue? { - return self.model.values["teamID"] + return model.values["teamID"] } func teamName() -> JSONValue? { - return self.model.values["team"]!["name"] + return model.values["team"]!["name"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/TeamWrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/TeamWrapper.swift index 167cb918b3..cbb2790907 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/TeamWrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/TeamWrapper.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: Team1 and Team 2 */ class TeamWrapper: NSCopying { var model: FlutterSerializedModel init(name: String) throws { - self.model = FlutterSerializedModel(id: UUID().uuidString, map: try FlutterDataStoreRequestUtils.getJSONValue(["name": name])) + self.model = try FlutterSerializedModel(id: UUID().uuidString, map: FlutterDataStoreRequestUtils.getJSONValue(["name": name])) } init(model: FlutterSerializedModel) { @@ -26,15 +26,15 @@ class TeamWrapper: NSCopying { } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func teamName() -> JSONValue? { - return self.model.values["name"] + return model.values["name"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/User5Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/User5Wrapper.swift index af8e5e097a..79c5f9e928 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/User5Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/User5Wrapper.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AmplifyTestCommon +import Foundation /** Creates a convenience wrapper for non-model type instantiations so that tests do not need to directly access json. - + Wraps: User5 */ class User5Wrapper: NSCopying { var model: FlutterSerializedModel init(id: String, username: String) throws { - self.model = FlutterSerializedModel(id: id, map: try FlutterDataStoreRequestUtils.getJSONValue(["username": username])) + self.model = try FlutterSerializedModel(id: id, map: FlutterDataStoreRequestUtils.getJSONValue(["username": username])) } init(model: FlutterSerializedModel) { @@ -26,15 +26,15 @@ class User5Wrapper: NSCopying { } func idString() -> String { - return self.model.id + return model.id } func id() -> JSONValue? { - return self.model.values["id"] + return model.values["id"] } func username() -> JSONValue? { - return self.model.values["username"] + return model.values["username"] } func copy(with zone: NSZone? = nil) -> Any { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SyncEngineFlutterIntegrationTestBase.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SyncEngineFlutterIntegrationTestBase.swift index b60c5bdef7..e02112129e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SyncEngineFlutterIntegrationTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SyncEngineFlutterIntegrationTestBase.swift @@ -4,11 +4,12 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest -@testable import DataStoreHostApp @testable import Amplify @testable import AmplifyTestCommon @testable import AWSDataStorePlugin +@testable import DataStoreHostApp class SyncEngineFlutterIntegrationTestBase: XCTestCase { @@ -67,8 +68,10 @@ class SyncEngineFlutterIntegrationTestBase: XCTestCase { let plugin: AWSDataStorePlugin = try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as! AWSDataStorePlugin var token: UnsubscribeToken! - token = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncStarted) { _ in + token = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncStarted + ) { _ in syncStarted.fulfill() Amplify.Hub.removeListener(token) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift index 3ca55b63cf..4583c39059 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift @@ -4,14 +4,15 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify import AmplifyTestCommon struct TestFlutterModelRegistration: AmplifyModelRegistration { var version: String = "1" - private let decoder: (String, JSONDecoder?) throws -> Model = { (jsonString, decoder) -> Model in + private let decoder: (String, JSONDecoder?) throws -> Model = { jsonString, decoder -> Model in let resolvedDecoder: JSONDecoder - if let decoder = decoder { + if let decoder { resolvedDecoder = decoder } else { resolvedDecoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) @@ -26,7 +27,8 @@ struct TestFlutterModelRegistration: AmplifyModelRegistration { return model } throw DataStoreError.decodingError( - "Error in decoding \(jsonString)", "Please create an issue to amplify-flutter repo.") + "Error in decoding \(jsonString)", "Please create an issue to amplify-flutter repo." + ) } func registerModels(registry: ModelRegistry.Type) { registry.register(modelType: Post.self, modelSchema: Post.schema, jsonDecoder: decoder) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/AWSDataStorePluginConfigurationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/AWSDataStorePluginConfigurationTests.swift index 1166319a9c..8600ec314b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/AWSDataStorePluginConfigurationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/AWSDataStorePluginConfigurationTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSDataStorePlugin import XCTest @testable import Amplify -import AWSDataStorePlugin class AWSDataStorePluginConfigurationTests: XCTestCase { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests+WatchOS.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests+WatchOS.swift index c2c3aeafb7..69b5e04186 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests+WatchOS.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests+WatchOS.swift @@ -8,24 +8,30 @@ import Foundation extension DataStoreConnectionScenario1Tests { - + #if os(watchOS) func testStartAndSync() async throws { - await setUp(withModels: TestModelRegistration(), - dataStoreConfiguration: .custom(syncMaxRecords: 100, disableSubscriptions: { true })) + await setUp( + withModels: TestModelRegistration(), + dataStoreConfiguration: .custom(syncMaxRecords: 100, disableSubscriptions: { true }) + ) try await startAmplifyAndWaitForSync() } func testSaveReconciled() async throws { - await setUp(withModels: TestModelRegistration(), - dataStoreConfiguration: .custom(syncMaxRecords: 100, disableSubscriptions: { true })) + await setUp( + withModels: TestModelRegistration(), + dataStoreConfiguration: .custom(syncMaxRecords: 100, disableSubscriptions: { true }) + ) try await startAmplifyAndWaitForSync() - + let team = Team1(name: "name1") let project = Project1(team: team) let syncedTeamReceived = expectation(description: "received team from sync path") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -43,10 +49,12 @@ extension DataStoreConnectionScenario1Tests { _ = try await Amplify.DataStore.save(team) await fulfillment(of: [syncedTeamReceived], timeout: networkTimeout) - + let syncProjectReceived = expectation(description: "received project from sync path") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -73,5 +81,5 @@ extension DataStoreConnectionScenario1Tests { XCTAssertEqual(queriedProject.team, team) } #endif - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests.swift index 49c5fb097e..46b8016f94 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario1Tests.swift @@ -32,24 +32,26 @@ import XCTest */ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { - + struct TestModelRegistration: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { registry.register(modelType: Team1.self) registry.register(modelType: Project1.self) } - + let version: String = "1" } - + func testSaveTeamAndProjectSyncToCloud() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() let team = Team1(name: "name1") let project = Project1(team: team) let syncedTeamReceived = expectation(description: "received team from sync path") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -67,10 +69,12 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { _ = try await Amplify.DataStore.save(team) await fulfillment(of: [syncedTeamReceived], timeout: networkTimeout) - + let syncProjectReceived = expectation(description: "received project from sync path") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -110,8 +114,10 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { _ = try await Amplify.DataStore.save(project) let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -129,7 +135,7 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { project.team = anotherTeam _ = try await Amplify.DataStore.save(project) await fulfillment(of: [syncUpdatedProjectReceived], timeout: networkTimeout) - + let queriedProjectOptional = try await Amplify.DataStore.query(Project1.self, byId: project.id) XCTAssertNotNil(queriedProjectOptional) if let queriedProject = queriedProjectOptional { @@ -141,14 +147,16 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { func testDeleteAndGetProjectReturnsNilWithSync() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team1(name: "name") let project = Project1(team: team) - + let createReceived = expectation(description: "received created items from cloud") createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -172,15 +180,17 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let deleteReceived = expectation(description: "Delete notification received") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -220,9 +230,9 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { let project = Project1(team: team) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + _ = try await Amplify.DataStore.delete(project, where: Project1.keys.team.eq(team.id)) - + let queriedProject = try await Amplify.DataStore.query(Project1.self, byId: project.id) XCTAssertNil(queriedProject) } @@ -258,7 +268,7 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { let project = Project1(team: team) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + let predicate = Project1.keys.team.eq(team.id) let projects = try await Amplify.DataStore.query(Project1.self, where: predicate) XCTAssertEqual(projects.count, 1) @@ -268,8 +278,10 @@ class DataStoreConnectionScenario1Tests: SyncEngineIntegrationTestBase { } extension Team1: Equatable { - public static func == (lhs: Team1, - rhs: Team1) -> Bool { + public static func == ( + lhs: Team1, + rhs: Team1 + ) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario2Tests.swift index 820b191aaf..f36fd0149f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario2Tests.swift @@ -50,8 +50,10 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { let project = Project2(teamID: team.id, team: team) let syncedTeamReceived = expectation(description: "received team from sync event") let syncProjectReceived = expectation(description: "received project from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -72,7 +74,7 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { _ = try await Amplify.DataStore.save(team) await fulfillment(of: [syncedTeamReceived], timeout: networkTimeout) - + _ = try await Amplify.DataStore.save(project) await fulfillment(of: [syncProjectReceived], timeout: networkTimeout) @@ -89,8 +91,10 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { var project = Project2(teamID: team.id, team: team) let expectedUpdatedProject = Project2(id: project.id, name: project.name, teamID: anotherTeam.id) let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -132,8 +136,10 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team let deleteReceived = expectation(description: "Delete notification received") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -202,7 +208,7 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { return } } - + let project2 = try await Amplify.DataStore.query(Project2.self, byId: project.id) XCTAssertNotNil(project2) } @@ -235,18 +241,22 @@ class DataStoreConnectionScenario2Tests: SyncEngineIntegrationTestBase { return try await Amplify.DataStore.save(team) } - func saveProject(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2? = nil) async throws -> Project2 { + func saveProject( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2? = nil + ) async throws -> Project2 { let project = Project2(id: id, name: name, teamID: teamID, team: team) return try await Amplify.DataStore.save(project) } } extension Team2: Equatable { - public static func == (lhs: Team2, - rhs: Team2) -> Bool { + public static func == ( + lhs: Team2, + rhs: Team2 + ) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario3Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario3Tests.swift index 15fc8f9d1f..5b57f45ed9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario3Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario3Tests.swift @@ -50,8 +50,10 @@ class DataStoreConnectionScenario3Tests: SyncEngineIntegrationTestBase { let comment = Comment3(postID: post.id, content: "content") let syncedPostReceived = expectation(description: "received post from sync event") let syncCommentReceived = expectation(description: "received comment from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -73,7 +75,7 @@ class DataStoreConnectionScenario3Tests: SyncEngineIntegrationTestBase { await fulfillment(of: [syncedPostReceived], timeout: networkTimeout) _ = try await Amplify.DataStore.save(comment) await fulfillment(of: [syncCommentReceived], timeout: networkTimeout) - + let queriedComment = try await Amplify.DataStore.query(Comment3.self, byId: comment.id) XCTAssertEqual(queriedComment, comment) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario4Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario4Tests.swift index 864a870bf9..0eb828c579 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario4Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario4Tests.swift @@ -107,7 +107,7 @@ class DataStoreConnectionScenario4Tests: SyncEngineIntegrationTestBase { let queriedComments = try await Amplify.DataStore.query(Comment4.self, where: predicate) XCTAssertEqual(queriedComments.count, 1) } - + func savePost(id: String = UUID().uuidString, title: String) async throws -> Post4 { let post = Post4(id: id, title: title) return try await Amplify.DataStore.save(post) @@ -120,8 +120,10 @@ class DataStoreConnectionScenario4Tests: SyncEngineIntegrationTestBase { } extension Post4: Equatable { - public static func == (lhs: Post4, - rhs: Post4) -> Bool { + public static func == ( + lhs: Post4, + rhs: Post4 + ) -> Bool { return lhs.id == rhs.id && lhs.title == rhs.title } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario5Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario5Tests.swift index 416db4b75f..a408e7fd35 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario5Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario5Tests.swift @@ -101,7 +101,7 @@ class DataStoreConnectionScenario5Tests: SyncEngineIntegrationTestBase { let post = try await savePost(title: "title") let user = try await saveUser(username: "username") _ = try await savePostEditor(post: post, editor: user) - + let queriedUserOptional = try await Amplify.DataStore.query(User5.self, byId: user.id) guard let queriedUser = queriedUserOptional else { XCTFail("Missing queried user") diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario6Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario6Tests.swift index 23158fdfa9..de6accc50e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario6Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Connection/DataStoreConnectionScenario6Tests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Combine +import XCTest @testable import Amplify @testable import AWSDataStorePlugin #if !os(watchOS) @@ -73,7 +73,7 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { } try await posts.fetch() XCTAssertEqual(posts.count, 2) - guard let fetchedPost = posts.first(where: { (post) -> Bool in + guard let fetchedPost = posts.first(where: { post -> Bool in post.id == post1.id }), let comments = fetchedPost.comments else { XCTFail("Could not set up - failed to get a post and its comments") @@ -81,10 +81,10 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { } try await comments.fetch() XCTAssertEqual(comments.count, 2) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment1post1.id })) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment2post1.id })) if let post = comments[0].post, let comments = post.comments { @@ -147,7 +147,7 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { if let postsInEagerlyLoadedBlog = eagerlyLoadedBlog.posts { try await postsInEagerlyLoadedBlog.fetch() XCTAssertEqual(postsInEagerlyLoadedBlog.count, 1) - XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {(postIn) -> Bool in + XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {postIn -> Bool in postIn.id == post.id })) XCTAssertEqual(postsInEagerlyLoadedBlog[0].id, post.id) @@ -183,7 +183,7 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { remoteEventReceived.expectedFulfillmentCount = 2 let commentId1 = UUID().uuidString let commentId2 = UUID().uuidString - + let task = Task { let mutationEvents = Amplify.DataStore.observe(Comment6.self) do { @@ -199,7 +199,7 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { XCTFail("Failed \(error)") } } - + let blog = try await saveBlog(name: "name") let post = try await savePost(title: "title", blog: blog) _ = try await saveComment(id: commentId1, post: post, content: "content") @@ -229,7 +229,7 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { model.id == commentId1 || model.id == commentId2 { processedSoFar += 1 } - + Amplify.Logging.verbose("Processed so far \(processedSoFar)/6") if processedSoFar == 6 { outboxMutationProcessed.fulfill() @@ -238,9 +238,9 @@ class DataStoreConnectionScenario6Tests: SyncEngineIntegrationTestBase { break } }.store(in: &cancellables) - + try await Amplify.DataStore.delete(Blog6.self, where: QueryPredicateConstant.all) - + await fulfillment(of: [outboxMutationProcessed], timeout: 30) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift index eb21319b2e..9328f10c27 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift @@ -34,11 +34,13 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let newPost = Post(title: "MyPost", - content: "This is my post.", - createdAt: .now(), - rating: 3, - status: .published) + let newPost = Post( + title: "MyPost", + content: "This is my post.", + createdAt: .now(), + rating: 3, + status: .published + ) var updatedPost = newPost updatedPost.rating = 5 @@ -49,7 +51,8 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return @@ -98,7 +101,7 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { 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) @@ -115,17 +118,20 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let newPost = Post(title: "MyPost", - content: "This is my post.", - createdAt: .now(), - rating: 3, - status: .published) + let newPost = Post( + title: "MyPost", + content: "This is my post.", + createdAt: .now(), + rating: 3, + status: .published + ) let deleteSyncReceived = expectation(description: "Received delete mutation event on subscription for Post") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return @@ -173,7 +179,7 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { XCTFail("Failed to get data") return } - + XCTAssertEqual(post.model["title"] as? String, newPost.title) XCTAssertEqual(post.model["content"] as? String, newPost.content) XCTAssertEqual(post.model["rating"] as? Double, newPost.rating) @@ -191,11 +197,13 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let newPost = Post(title: "MyPost", - content: "This is my post.", - createdAt: .now(), - rating: 3, - status: .published) + let newPost = Post( + title: "MyPost", + content: "This is my post.", + createdAt: .now(), + rating: 3, + status: .published + ) var updatedPost = newPost updatedPost.rating = 5 @@ -279,11 +287,13 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let newPost = Post(title: "MyPost", - content: "This is my post.", - createdAt: .now(), - rating: 3, - status: .published) + let newPost = Post( + title: "MyPost", + content: "This is my post.", + createdAt: .now(), + rating: 3, + status: .published + ) var updatedPost = newPost let updatedPostDefaultTitle = "MyUpdatedPost" let updateCount = 10 @@ -293,7 +303,8 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return @@ -348,7 +359,7 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { 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) @@ -360,7 +371,7 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { XCTFail("Error: \(error)") } } - + func queryPost(byId id: String) async throws -> Post? { return try await Amplify.DataStore.query(Post.self, byId: id) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift index 1c89de647a..2728af6467 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift @@ -42,7 +42,8 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { updatedCustomerOrder.email = "testnew@abc.com" var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -50,7 +51,8 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { } guard let order = try? mutationEvent.decodeModel() as? CustomerOrder, - order.id == customerOrder.id else { + order.id == customerOrder.id + else { return } @@ -75,7 +77,8 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { let updateReceived = expectation(description: "Update notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -83,11 +86,12 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { } guard let order = try? mutationEvent.decodeModel() as? CustomerOrder, - order.id == customerOrder.id else { + order.id == customerOrder.id + else { return } - + if mutationEvent.mutationType == GraphQLMutationType.update.rawValue { XCTAssertEqual(order.email, updatedCustomerOrder.email) XCTAssertEqual(order.orderId, updatedCustomerOrder.orderId) @@ -113,12 +117,13 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { XCTAssertEqual(order.id, updatedCustomerOrder.id) XCTAssertEqual(order.orderId, updatedCustomerOrder.orderId) XCTAssertEqual(order.email, updatedCustomerOrder.email) - + // delete the customer order let deleteReceived = expectation(description: "Delete notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -126,7 +131,8 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { } guard let order = try? mutationEvent.decodeModel() as? CustomerOrder, - order.id == customerOrder.id else { + order.id == customerOrder.id + else { return } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift index a23a537dd1..86b609a06f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift @@ -35,7 +35,7 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { XCTFail("Error \(error)") } } - + func testCreate() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForReady() @@ -44,7 +44,8 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post( title: "This is a new post I created", content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: date) + createdAt: date + ) let outboxMutationEnqueued = expectation(description: "received OutboxMutationEnqueuedEvent") outboxMutationEnqueued.assertForOverFulfill = false @@ -127,7 +128,8 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post( title: "This is a new post I created", content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: date) + createdAt: date + ) var updatedPost = newPost updatedPost.content = "UPDATED CONTENT from DataStoreEndToEndTests at \(Date())" @@ -135,7 +137,8 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let createReceived = expectation(description: "Create notification received") var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -166,7 +169,8 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let updateReceived = expectation(description: "Update notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -192,11 +196,12 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { } _ = try await Amplify.DataStore.save(updatedPost) await fulfillment(of: [updateReceived], timeout: networkTimeout) - + let deleteReceived = expectation(description: "Delete notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -238,14 +243,16 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post( title: title, content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: date) + createdAt: date + ) var updatedPost = newPost updatedPost.content = "UPDATED CONTENT from DataStoreEndToEndTests at \(Date())" let createReceived = expectation(description: "Create notification received") var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -271,11 +278,12 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { } _ = try await Amplify.DataStore.save(newPost) await fulfillment(of: [createReceived], timeout: networkTimeout) - + let updateReceived = expectation(description: "Update notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -320,7 +328,8 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post( title: title, content: "Original content from DataStoreEndToEndTests at \(date.iso8601String)", - createdAt: date) + createdAt: date + ) var updatedPost = newPost updatedPost.content = "UPDATED CONTENT from DataStoreEndToEndTests at \(Date())" @@ -358,7 +367,7 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { _ = try await Amplify.DataStore.save(newPost) await fulfillment(of: [createReceived], timeout: networkTimeout) - + let updateLocalSuccess = expectation(description: "Update local successful") storageAdapter.save(updatedPost) { result in switch result { @@ -397,7 +406,7 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(updatedPost, where: post.content == updatedPost.content) await fulfillment(of: [conditionalReceived], timeout: networkTimeout) @@ -419,7 +428,7 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { try await Amplify.DataStore.start() try await validateSavePost() } - + /// Ensure DataStore.stop followed by DataStore.start is successful /// /// - Given: DataStore has just configured, but not yet started @@ -542,12 +551,11 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post(title: UUID().uuidString, content: UUID().uuidString, createdAt: .now()) let titlePrefix = UUID().uuidString - let posts = (0..() let extractPost: (DataStoreHubEvent) -> Post? = { if case .outboxMutationProcessed(let mutationEvent) = $0, - mutationEvent.modelName == Post.modelName - { + mutationEvent.modelName == Post.modelName { return mutationEvent.element.model as? Post } return nil @@ -661,11 +669,13 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { let newPost = Post( title: "This is a new post I created", content: "Original content from DataStoreEndToEndTests at \(date)", - createdAt: date) + createdAt: date + ) let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -692,7 +702,7 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { } _ = try await Amplify.DataStore.save(newPost) - + await fulfillment(of: [createReceived], timeout: networkTimeout) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreHubEventsTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreHubEventsTests.swift index a5fe3115f4..b68ca9615b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreHubEventsTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreHubEventsTests.swift @@ -170,7 +170,8 @@ class DataStoreHubEventTests: HubEventsIntegrationTestBase { if modelSyncedEvents.count == 2 { guard let postModelSyncedEvent = modelSyncedEvents.first(where: { $0.modelName == "Post" }), - let commentModelSyncedEvent = modelSyncedEvents.first(where: { $0.modelName == "Comment" }) else { + let commentModelSyncedEvent = modelSyncedEvents.first(where: { $0.modelName == "Comment" }) + else { XCTFail("Could not get modelSyncedEvent for Post and Comment") return } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreLargeNumberModelsSubscriptionTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreLargeNumberModelsSubscriptionTests.swift index 4121f562bd..d18f61b52e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreLargeNumberModelsSubscriptionTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreLargeNumberModelsSubscriptionTests.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - -import XCTest -import Combine import Amplify +import Combine +import XCTest @testable import AWSAPIPlugin class DataStoreLargeNumberModelsSubscriptionTests: SyncEngineIntegrationTestBase { @@ -56,8 +55,8 @@ class DataStoreLargeNumberModelsSubscriptionTests: SyncEngineIntegrationTestBase let repeatCount = 5 await setUp(withModels: TestModelRegistration()) try startAmplify() - - for _ in 0..() - + struct TestModelRegistration: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { registry.register(modelType: Post.self) @@ -61,8 +61,10 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { querySnapshotsCancelled.fulfill() } let receivedPost = expectation(description: "received Post") - try await savePostAndWaitForSync(Post(title: "title", content: "content", createdAt: .now()), - postSyncedExpctation: receivedPost) + try await savePostAndWaitForSync( + Post(title: "title", content: "content", createdAt: .now()), + postSyncedExpctation: receivedPost + ) await fulfillment(of: [snapshotWithIsSynced], timeout: 100) task.cancel() await fulfillment(of: [querySnapshotsCancelled], timeout: 10) @@ -108,7 +110,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { postSyncedExpctation: receivedPost ) await fulfillment(of: [snapshotWithIsSynced], timeout: 100) - + XCTAssertTrue(snapshots.count >= 2) XCTAssertFalse(snapshots[0].isSynced) } @@ -151,7 +153,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { } }.store(in: &cancellables) await fulfillment(of: [observeQueryReadyForTest], timeout: 100) - + _ = try await Amplify.DataStore.save(post) await fulfillment(of: [snapshotWithPost], timeout: 100) } @@ -175,7 +177,8 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { modelPredicate: { Post.keys.createdAt.ge(startTime) } ) ], - disableSubscriptions: { false }) + disableSubscriptions: { false } + ) #else let configuration: DataStoreConfiguration = .custom( syncMaxRecords: 100, @@ -184,7 +187,8 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { modelSchema: Post.schema, modelPredicate: { Post.keys.createdAt.ge(startTime) } ) - ]) + ] + ) #endif await setUp( withModels: TestModelRegistration(), @@ -223,19 +227,18 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { snapshotWithIsSynced.fulfill() } else if snapshotWithIsSyncedFulfilled { if querySnapshot.items.count >= 4 - && querySnapshot.items.allSatisfy({ $0.title.contains(randomTitle)}) - { + && querySnapshot.items.allSatisfy({ $0.title.contains(randomTitle)}) { receivedPostFromObserveQuery.fulfill() } } - + }.store(in: &cancellables) await fulfillment(of: [snapshotWithIsSynced], timeout: 100) try await savePostAndWaitForSync(post4) await fulfillment(of: [receivedPostFromObserveQuery], timeout: 100) - + XCTAssertTrue(snapshots.count >= 2) } @@ -315,8 +318,10 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { } }.store(in: &cancellables) let receivedPost = expectation(description: "received Post") - try await savePostAndWaitForSync(Post(title: "title", content: "content", createdAt: .now()), - postSyncedExpctation: receivedPost) + try await savePostAndWaitForSync( + Post(title: "title", content: "content", createdAt: .now()), + postSyncedExpctation: receivedPost + ) await fulfillment(of: [snapshotWithIsSynced], timeout: 30) XCTAssertTrue(snapshots.count >= 2) XCTAssertFalse(snapshots[0].isSynced) @@ -360,8 +365,10 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { let newPost = Post(title: "title", content: "content", createdAt: .now()) let receivedPost = expectation(description: "received Post") - try await savePostAndWaitForSync(newPost, - postSyncedExpctation: receivedPost) + try await savePostAndWaitForSync( + newPost, + postSyncedExpctation: receivedPost + ) await fulfillment(of: [snapshotWithIsSynced], timeout: 30) XCTAssertTrue(snapshots.count >= 2) @@ -445,13 +452,13 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { } }.store(in: &cancellables) await fulfillment(of: [snapshotExpectation1], timeout: 10) - + // (1) Add model that matches predicate - should be received on the snapshot let postMatchPredicate = Post(title: "xyz 1", content: testId, createdAt: .now()) - + try await savePostAndWaitForSync(postMatchPredicate) await fulfillment(of: [snapshotExpectation23], timeout: 10) - + // (2) Add model that does not match predicate - should not be received on the snapshot // (3) Update model that used to match the predicate to no longer match - should be removed from snapshot let postDoesNotMatch = Post(title: "doesNotMatch", content: testId, createdAt: .now()) @@ -461,21 +468,23 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { postMatchPredicateNoLongerMatches.title = "doesNotMatch" try await savePostAndWaitForSync(postMatchPredicateNoLongerMatches) await fulfillment(of: [snapshotExpectation4], timeout: 10) - + // (4) Update model that does not match predicate to match - should be added to snapshot var postDoesNotMatchNowMatches = postDoesNotMatch postDoesNotMatchNowMatches.title = "xyz 2" try await savePostAndWaitForSync(postDoesNotMatchNowMatches) await fulfillment(of: [snapshotExpectation56], timeout: 10) - + // (5) Delete the model that matches the predicate - should be removed try await deletePostAndWaitForSync(postDoesNotMatchNowMatches) await fulfillment(of: [snapshotExpectation7], timeout: 10) - + // (6) Delete the model that does not match predicate - should have no snapshot emitted let postMatchPredicateNoLongerMatchesExpectation = expectation(description: " received") - try await deletePostAndWaitForSync(postMatchPredicateNoLongerMatches, - postSyncedExpctation: postMatchPredicateNoLongerMatchesExpectation) + try await deletePostAndWaitForSync( + postMatchPredicateNoLongerMatches, + postSyncedExpctation: postMatchPredicateNoLongerMatchesExpectation + ) // Save "xyz 3" to force a snapshot to be emitted try await savePostAndWaitForSync(Post(title: "xyz 3", content: testId, createdAt: .now())) @@ -501,9 +510,11 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { var snapshotCount = 0 let observeQueryReadyForTest = expectation(description: "observeQuery initial query completed") let allSnapshotsReceived = expectation(description: "query snapshots received") - let sink = Amplify.Publisher.create(Amplify.DataStore.observeQuery(for: Post.self, - where: Post.keys.content == testId, - sort: .ascending(Post.keys.title))) + let sink = Amplify.Publisher.create(Amplify.DataStore.observeQuery( + for: Post.self, + where: Post.keys.content == testId, + sort: .ascending(Post.keys.title) + )) .sink { completed in switch completed { case .finished: @@ -607,7 +618,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { } }.store(in: &cancellables) await fulfillment(of: [firstSnapshotWithIsSynced], timeout: 10) - + let observeQueryReceivedCompleted = expectation(description: "observeQuery received completed") observeQueryReceivedCompleted.isInverted = true onComplete = { completed in @@ -642,7 +653,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { } }.store(in: &cancellables) await fulfillment(of: [firstSnapshotWithIsSynced], timeout: 100) - + let observeQueryReceivedCompleted = expectation(description: "observeQuery received completed") observeQueryReceivedCompleted.isInverted = true onComplete = { completed in @@ -711,7 +722,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { XCTFail("Failed \(error)") } } - + _ = try await Amplify.DataStore.save(post) await fulfillment(of: [receivedPost], timeout: 100) } @@ -738,7 +749,7 @@ class DataStoreObserveQueryTests: SyncEngineIntegrationTestBase { XCTFail("Failed \(error)") } } - + _ = try await Amplify.DataStore.delete(post) await fulfillment(of: [deletedPost], timeout: 100) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreScalarTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreScalarTests.swift index e24629883f..8e04331ba3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreScalarTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreScalarTests.swift @@ -27,19 +27,21 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { func testScalarContainer() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let container = ScalarContainer(myString: "myString", - myInt: 1, - myDouble: 1.0, - myBool: true, - myDate: .now(), - myTime: .now(), - myDateTime: .now(), - myTimeStamp: 123, - myEmail: "local-part@domain-part", - myJSON: "{}", - myPhone: "2342355678", - myURL: "https://www.amazon.com/dp/B000NZW3KC/", - myIPAddress: "123.12.34.56") + let container = ScalarContainer( + myString: "myString", + myInt: 1, + myDouble: 1.0, + myBool: true, + myDate: .now(), + myTime: .now(), + myDateTime: .now(), + myTimeStamp: 123, + myEmail: "local-part@domain-part", + myJSON: "{}", + myPhone: "2342355678", + myURL: "https://www.amazon.com/dp/B000NZW3KC/", + myIPAddress: "123.12.34.56" + ) let updatedContainer = ScalarContainer(id: container.id) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) @@ -61,15 +63,18 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { intList: [], intNullableList: [], nullableIntList: [], - nullableIntNullableList: nil) - - let updatedContainer = ListIntContainer(id: container.id, - test: 2, - nullableInt: nil, - intList: [1, 2, 3], - intNullableList: [1, 2, 3], - nullableIntList: [1, 2, 3], - nullableIntNullableList: [1, 2, 3]) + nullableIntNullableList: nil + ) + + let updatedContainer = ListIntContainer( + id: container.id, + test: 2, + nullableInt: nil, + intList: [1, 2, 3], + intNullableList: [1, 2, 3], + nullableIntList: [1, 2, 3], + nullableIntNullableList: [1, 2, 3] + ) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) let updatedModel = try await Amplify.DataStore.save(updatedContainer) @@ -90,15 +95,18 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { stringList: ["value1"], stringNullableList: [], nullableStringList: [], - nullableStringNullableList: nil) - - let updatedContainer = ListStringContainer(id: container.id, - test: "test", - nullableString: "test", - stringList: ["value1"], - stringNullableList: ["value1"], - nullableStringList: ["value1"], - nullableStringNullableList: ["value1"]) + nullableStringNullableList: nil + ) + + let updatedContainer = ListStringContainer( + id: container.id, + test: "test", + nullableString: "test", + stringList: ["value1"], + stringNullableList: ["value1"], + nullableStringList: ["value1"], + nullableStringNullableList: ["value1"] + ) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) let updatedModel = try await Amplify.DataStore.save(updatedContainer) @@ -120,15 +128,18 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { stringList: ["value1"], stringNullableList: nil, nullableStringList: [nil], - nullableStringNullableList: nil) - - let updatedContainer = ListStringContainer(id: container.id, - test: "test", - nullableString: "test", - stringList: ["value1"], - stringNullableList: ["value1"], - nullableStringList: ["value1"], - nullableStringNullableList: ["value1"]) + nullableStringNullableList: nil + ) + + let updatedContainer = ListStringContainer( + id: container.id, + test: "test", + nullableString: "test", + stringList: ["value1"], + stringNullableList: ["value1"], + nullableStringList: ["value1"], + nullableStringNullableList: ["value1"] + ) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) let updatedModel = try await Amplify.DataStore.save(updatedContainer) @@ -143,19 +154,23 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { func testEnumTestModel() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let container = EnumTestModel(enumVal: .valueOne, - nullableEnumVal: .valueTwo, - enumList: [.valueOne], - enumNullableList: [.valueTwo], - nullableEnumList: [.valueOne, .valueTwo], - nullableEnumNullableList: [.valueTwo, .valueOne]) - let updatedContainer = EnumTestModel(id: container.id, - enumVal: .valueTwo, - nullableEnumVal: nil, - enumList: [.valueTwo], - enumNullableList: [.valueTwo, .valueOne], - nullableEnumList: [.valueTwo, .valueOne], - nullableEnumNullableList: [.valueOne, .valueTwo]) + let container = EnumTestModel( + enumVal: .valueOne, + nullableEnumVal: .valueTwo, + enumList: [.valueOne], + enumNullableList: [.valueTwo], + nullableEnumList: [.valueOne, .valueTwo], + nullableEnumNullableList: [.valueTwo, .valueOne] + ) + let updatedContainer = EnumTestModel( + id: container.id, + enumVal: .valueTwo, + nullableEnumVal: nil, + enumList: [.valueTwo], + enumNullableList: [.valueTwo, .valueOne], + nullableEnumList: [.valueTwo, .valueOne], + nullableEnumNullableList: [.valueOne, .valueTwo] + ) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) let updatedModel = try await Amplify.DataStore.save(updatedContainer) @@ -170,20 +185,24 @@ class DataStoreScalarTests: SyncEngineIntegrationTestBase { func testNestedEnumTestModel() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - let container = NestedTypeTestModel(nestedVal: .init(valueOne: 1), - nullableNestedVal: .init(), - nestedList: [.init(valueTwo: "value2")], - nestedNullableList: [.init()], - nullableNestedList: [.init(valueOne: 1, valueTwo: "value2")], - nullableNestedNullableList: [.init(valueOne: 1, valueTwo: "value2")]) - - let updatedContainer = NestedTypeTestModel(id: container.id, - nestedVal: .init(valueOne: 1), - nullableNestedVal: .init(), - nestedList: [.init(valueTwo: "updatedValue"), .init(valueOne: 1)], - nestedNullableList: [.init(valueOne: 1, valueTwo: "value2")], - nullableNestedList: [], - nullableNestedNullableList: nil) + let container = NestedTypeTestModel( + nestedVal: .init(valueOne: 1), + nullableNestedVal: .init(), + nestedList: [.init(valueTwo: "value2")], + nestedNullableList: [.init()], + nullableNestedList: [.init(valueOne: 1, valueTwo: "value2")], + nullableNestedNullableList: [.init(valueOne: 1, valueTwo: "value2")] + ) + + let updatedContainer = NestedTypeTestModel( + id: container.id, + nestedVal: .init(valueOne: 1), + nullableNestedVal: .init(), + nestedList: [.init(valueTwo: "updatedValue"), .init(valueOne: 1)], + nestedNullableList: [.init(valueOne: 1, valueTwo: "value2")], + nullableNestedList: [], + nullableNestedNullableList: nil + ) let savedModel = try await Amplify.DataStore.save(container) XCTAssertEqual(savedModel, container) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/AmplifyModels.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/AmplifyModels.swift index 2f95bb74f4..20d39f3f52 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/AmplifyModels.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/AmplifyModels.swift @@ -11,7 +11,7 @@ import Foundation // Contains the set of classes that conforms to the `Model` protocol. -final public class AmplifyModels: AmplifyModelRegistration { +public final class AmplifyModels: AmplifyModelRegistration { public let version: String public init(version: String = "46369a50a95486d76713fd33833fb782") { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article+Schema.swift index 251a7dfe2c..bb0d8d1529 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Article { +public extension Article { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt @@ -19,10 +19,10 @@ extension Article { case authorNotes } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let article = Article.keys model.listPluralName = "Articles" @@ -38,10 +38,11 @@ extension Article { .field(article.content, is: .required, ofType: .string), .field(article.createdAt, is: .required, ofType: .dateTime), .field(article.owner, is: .optional, ofType: .string), - .field(article.authorNotes, - is: .optional, - ofType: .string, - authRules: [rule(allow: .owner, ownerField: "owner", operations: [.update])] + .field( + article.authorNotes, + is: .optional, + ofType: .string, + authRules: [rule(allow: .owner, ownerField: "owner", operations: [.update])] ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article.swift index 5b1486510a..84661e4cfc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Article.swift @@ -16,11 +16,13 @@ public struct Article: Model { public var owner: String? public var authorNotes: String? - public init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime, - owner: String?, - authorNotes: String?) { + public init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime, + owner: String?, + authorNotes: String? + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author+Schema.swift index 9d64613c81..3b253b6aa8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author+Schema.swift @@ -8,26 +8,28 @@ import Amplify import Foundation -extension Author { +public extension Author { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case books } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let author = Author.keys model.fields( .id(), - .hasMany(author.books, - ofType: BookAuthor.self, - associatedWith: BookAuthor.keys.book) + .hasMany( + author.books, + ofType: BookAuthor.self, + associatedWith: BookAuthor.keys.book + ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author.swift index de80ddf0ec..2aaaf7bdc8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Author.swift @@ -15,8 +15,10 @@ public struct Author: Model { // hasMany(associatedWith: "author") public var books: List - public init(id: String = UUID().uuidString, - books: List = []) { + public init( + id: String = UUID().uuidString, + books: List = [] + ) { self.id = id self.books = books } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book+Schema.swift index 72c6af2f9d..4854747fe9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book+Schema.swift @@ -8,26 +8,28 @@ import Amplify import Foundation -extension Book { +public extension Book { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case authors } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let book = Book.keys model.fields( .id(), - .hasMany(book.authors, - ofType: BookAuthor.self, - associatedWith: BookAuthor.keys.author) + .hasMany( + book.authors, + ofType: BookAuthor.self, + associatedWith: BookAuthor.keys.author + ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book.swift index d2d130e83a..51be34c79f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/Book.swift @@ -15,8 +15,10 @@ public struct Book: Model { // hasMany(associatedWith: "book") public var authors: List - public init(id: String = UUID().uuidString, - authors: List = []) { + public init( + id: String = UUID().uuidString, + authors: List = [] + ) { self.id = id self.authors = authors } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor+Schema.swift index 52600e0a9d..2b048a1ca6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor+Schema.swift @@ -8,30 +8,34 @@ import Amplify import Foundation -extension BookAuthor { +public extension BookAuthor { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case book case author } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let bookAuthor = BookAuthor.keys model.fields( .id(), - .belongsTo(bookAuthor.book, - ofType: Book.self, - associatedWith: Book.keys.authors), - .belongsTo(bookAuthor.author, - ofType: Author.self, - associatedWith: Author.keys.books) + .belongsTo( + bookAuthor.book, + ofType: Book.self, + associatedWith: Book.keys.authors + ), + .belongsTo( + bookAuthor.author, + ofType: Author.self, + associatedWith: Author.keys.books + ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor.swift index 1c837b590c..e29875b031 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/BookAuthor.swift @@ -18,9 +18,11 @@ public struct BookAuthor: Model { // belongsTo public let book: Book - public init(id: String = UUID().uuidString, - book: Book, - author: Author) { + public init( + id: String = UUID().uuidString, + book: Book, + author: Author + ) { self.id = id self.book = book self.author = author diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount+Schema.swift index dc51cd80e0..adf7fb3f85 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount+Schema.swift @@ -8,27 +8,29 @@ import Amplify import Foundation -extension UserAccount { +public extension UserAccount { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case profile } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let account = UserAccount.keys model.fields( .id(), - .hasOne(account.profile, - is: .optional, - ofType: UserProfile.self, - associatedWith: UserProfile.CodingKeys.account) + .hasOne( + account.profile, + is: .optional, + ofType: UserProfile.self, + associatedWith: UserProfile.CodingKeys.account + ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount.swift index 268b5f0fed..a05e352f88 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserAccount.swift @@ -20,8 +20,10 @@ public class UserAccount: Model { // hasOne(associatedWith: "account") public var profile: UserProfile? - public init(id: String = UUID().uuidString, - profile: UserProfile? = nil) { + public init( + id: String = UUID().uuidString, + profile: UserProfile? = nil + ) { self.id = id self.profile = profile } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile+Schema.swift index 6b6eb355d7..d4e2c7ee1d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile+Schema.swift @@ -8,26 +8,28 @@ import Amplify import Foundation -extension UserProfile { +public extension UserProfile { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case account } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let profile = UserProfile.keys model.fields( .id(), - .belongsTo(profile.account, - ofType: UserAccount.self, - associatedWith: UserAccount.keys.profile) + .belongsTo( + profile.account, + ofType: UserAccount.self, + associatedWith: UserAccount.keys.profile + ) ) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile.swift index 227d1c8da5..26d1d2e7cb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Associations/UserProfile.swift @@ -20,8 +20,10 @@ public class UserProfile: Model { // belongsTo(associatedWith: "profile") public var account: UserAccount - public init(id: String = UUID().uuidString, - account: UserAccount) { + public init( + id: String = UUID().uuidString, + account: UserAccount + ) { self.id = id self.account = account } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1+Schema.swift index d561583928..7d0aacab8b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Project1 { +public extension Project1 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project1 = Project1.keys model.listPluralName = "Project1s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1.swift index ab67718c80..8760364532 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Project1.swift @@ -14,9 +14,11 @@ public struct Project1: Model { public var name: String? public var team: Team1? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String? = nil, - team: Team1? = nil) { + team: Team1? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1+Schema.swift index be252d9197..946b4692c0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1+Schema.swift @@ -9,17 +9,17 @@ import Amplify import Foundation -extension Team1 { +public extension Team1 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team1 = Team1.keys model.listPluralName = "Team1s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1.swift index 4a6101a50c..0bcf352358 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/1/Team1.swift @@ -13,8 +13,10 @@ public struct Team1: Model { public let id: String public var name: String - public init(id: String = UUID().uuidString, - name: String) { + public init( + id: String = UUID().uuidString, + name: String + ) { self.id = id self.name = name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2+Schema.swift index 7bd2fd74ce..837b30544e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Project2 { +public extension Project2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case teamID case team } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project2 = Project2.keys model.listPluralName = "Project2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2.swift index a5307b612c..0dbc730331 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Project2.swift @@ -15,10 +15,12 @@ public struct Project2: Model { public var teamID: String public var team: Team2? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String? = nil, teamID: String, - team: Team2? = nil) { + team: Team2? = nil + ) { self.id = id self.name = name self.teamID = teamID diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2+Schema.swift index 9c7424a94d..4e97ad88c6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2+Schema.swift @@ -9,17 +9,17 @@ import Amplify import Foundation -extension Team2 { +public extension Team2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team2 = Team2.keys model.listPluralName = "Team2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2.swift index eece17c222..7c3b6617a8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/2/Team2.swift @@ -13,8 +13,10 @@ public struct Team2: Model { public let id: String public var name: String - public init(id: String = UUID().uuidString, - name: String) { + public init( + id: String = UUID().uuidString, + name: String + ) { self.id = id self.name = name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3+Schema.swift index 03c4b0eb64..f2be1939c8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Comment3 { +public extension Comment3 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case postID case content } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment3 = Comment3.keys model.listPluralName = "Comment3s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3.swift index f24badf993..14c2cce660 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Comment3.swift @@ -14,9 +14,11 @@ public struct Comment3: Model { public var postID: String public var content: String - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, postID: String, - content: String) { + content: String + ) { self.id = id self.postID = postID self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3+Schema.swift index 9f828c7c44..fbda57a013 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Post3 { +public extension Post3 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post3 = Post3.keys model.listPluralName = "Post3s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3.swift index 1302c5a233..63d64a9316 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/3/Post3.swift @@ -14,9 +14,11 @@ public struct Post3: Model { public var title: String public var comments: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - comments: List? = []) { + comments: List? = [] + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4+Schema.swift index 16b6b2a416..35b7c9278c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Comment4 { +public extension Comment4 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment4 = Comment4.keys model.listPluralName = "Comment4s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4.swift index 175c4d994a..a404407183 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Comment4.swift @@ -14,9 +14,11 @@ public struct Comment4: Model { public var content: String public var post: Post4? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, content: String, - post: Post4? = nil) { + post: Post4? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4+Schema.swift index 17144a90a0..ac5c751832 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Post4 { +public extension Post4 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post4 = Post4.keys model.listPluralName = "Post4s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4.swift index 4764058a79..84fc6972ba 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/4/Post4.swift @@ -14,9 +14,11 @@ public struct Post4: Model { public var title: String public var comments: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - comments: List? = []) { + comments: List? = [] + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5+Schema.swift index 3898f6addd..419ffc556d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Post5 { +public extension Post5 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case editors } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post5 = Post5.keys model.listPluralName = "Post5s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5.swift index 023c8eb0dc..d4f8fc51fa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/Post5.swift @@ -14,9 +14,11 @@ public struct Post5: Model { public var title: String public var editors: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - editors: List? = []) { + editors: List? = [] + ) { self.id = id self.title = title self.editors = editors diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5+Schema.swift index 586429c143..2d054312a0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension PostEditor5 { +public extension PostEditor5 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post case editor } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let postEditor5 = PostEditor5.keys model.listPluralName = "PostEditor5s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5.swift index 24cad3a416..30af2f8558 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/PostEditor5.swift @@ -14,9 +14,11 @@ public struct PostEditor5: Model { public var post: Post5 public var editor: User5 - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, post: Post5, - editor: User5) { + editor: User5 + ) { self.id = id self.post = post self.editor = editor diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5+Schema.swift index cf467b9f55..431a0027db 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension User5 { +public extension User5 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case username case posts } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let user5 = User5.keys model.listPluralName = "User5s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5.swift index 3fab8d8d27..63e5ad8478 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/5/User5.swift @@ -14,9 +14,11 @@ public struct User5: Model { public var username: String public var posts: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, username: String, - posts: List? = []) { + posts: List? = [] + ) { self.id = id self.username = username self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6+Schema.swift index fc6b58b600..af044289e0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Blog6 { +public extension Blog6 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog6 = Blog6.keys model.listPluralName = "Blog6s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6.swift index 9bc903c6d4..d226a82190 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Blog6.swift @@ -14,9 +14,11 @@ public struct Blog6: Model { public var name: String public var posts: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String, - posts: List? = []) { + posts: List? = [] + ) { self.id = id self.name = name self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6+Schema.swift index 3d180ac245..ef05fae7ca 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Comment6 { +public extension Comment6 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post case content } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment6 = Comment6.keys model.listPluralName = "Comment6s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6.swift index 061c288aa1..960b55edd1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Comment6.swift @@ -14,9 +14,11 @@ public struct Comment6: Model { public var post: Post6? public var content: String - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, post: Post6? = nil, - content: String) { + content: String + ) { self.id = id self.post = post self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6+Schema.swift index e84aa85350..24956ef8f6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Post6 { +public extension Post6 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case blog case comments } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post6 = Post6.keys model.listPluralName = "Post6s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6.swift index a470246a15..122eebf379 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Collection/6/Post6.swift @@ -15,10 +15,12 @@ public struct Post6: Model { public var blog: Blog6? public var comments: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, blog: Blog6? = nil, - comments: List? = []) { + comments: List? = [] + ) { self.id = id self.title = title self.blog = blog diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment+Schema.swift index 97c63c8661..e50f2f4c35 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Comment { +public extension Comment { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt case post } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment = Comment.keys model.listPluralName = "Comments" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment.swift index 51db95f439..58b9cc17ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Comment.swift @@ -15,10 +15,12 @@ public struct Comment: Model { public var createdAt: Temporal.DateTime public var post: Post - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, content: String, createdAt: Temporal.DateTime, - post: Post) { + post: Post + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder+Schema.swift index 2bd91ddb85..36b482fc13 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension CustomerOrder { +public extension CustomerOrder { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case orderId case email } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerOrder = CustomerOrder.keys model.listPluralName = "CustomerOrders" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder.swift index 92609d0848..2e3472728a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/CustomerOrder.swift @@ -22,9 +22,11 @@ public struct CustomerOrder: Model { public var orderId: String public var email: String - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, orderId: String, - email: String) { + email: String + ) { self.id = id self.orderId = orderId self.email = email diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Deprecated/DeprecatedTodo.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Deprecated/DeprecatedTodo.swift index 2e364e24d6..53a88d40c5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Deprecated/DeprecatedTodo.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Deprecated/DeprecatedTodo.swift @@ -8,6 +8,7 @@ // swiftlint:disable all import Amplify import Foundation + /* The schema used to codegen this model: type DeprecatedTodo @model { @@ -30,27 +31,29 @@ public struct DeprecatedTodo: Model { public var description: String? public var note: Note? - public init(id: String = UUID().uuidString, - description: String? = nil, - note: Note? = nil) { + public init( + id: String = UUID().uuidString, + description: String? = nil, + note: Note? = nil + ) { self.id = id self.description = description self.note = note } } -extension DeprecatedTodo { +public extension DeprecatedTodo { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case description case note } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let deprecatedTodo = DeprecatedTodo.keys model.pluralName = "DeprecatedTodos" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost+Schema.swift index 7d700109e9..c9a94931a5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension M2MPost { +public extension M2MPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case editors } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let m2MPost = M2MPost.keys model.listPluralName = "M2MPosts" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost.swift index 38b678400f..12862030b3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPost.swift @@ -14,9 +14,11 @@ public struct M2MPost: Model { public var title: String public var editors: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - editors: List? = []) { + editors: List? = [] + ) { self.id = id self.title = title self.editors = editors diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor+Schema.swift index 7c48259298..d37c0719cb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension M2MPostEditor { +public extension M2MPostEditor { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post case editor } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let m2MPostEditor = M2MPostEditor.keys model.listPluralName = "M2MPostEditors" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor.swift index f90b4ec386..2cfd57b223 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MPostEditor.swift @@ -14,9 +14,11 @@ public struct M2MPostEditor: Model { public var post: M2MPost public var editor: M2MUser - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, post: M2MPost, - editor: M2MUser) { + editor: M2MUser + ) { self.id = id self.post = post self.editor = editor diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser+Schema.swift index 452ca2b270..1db74f78b5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension M2MUser { +public extension M2MUser { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case username case posts } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let m2MUser = M2MUser.keys model.listPluralName = "M2MUsers" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser.swift index 076f5fb3b5..4c62eb0f75 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/M2MPostEditorUser/M2MUser.swift @@ -14,9 +14,11 @@ public struct M2MUser: Model { public var username: String public var posts: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, username: String, - posts: List? = []) { + posts: List? = [] + ) { self.id = id self.username = username self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Category.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Category.swift index 277b136bf2..3f5375f2db 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Category.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Category.swift @@ -14,18 +14,20 @@ public struct Category: Embeddable { var color: Color } -extension Category { +public extension Category { - public enum CodingKeys: CodingKey { + enum CodingKeys: CodingKey { case name case color } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self - public static let schema = defineSchema { embedded in + static let schema = defineSchema { embedded in let category = Category.keys - embedded.fields(.field(category.name, is: .required, ofType: .string), - .field(category.color, is: .required, ofType: .embedded(type: Color.self))) + embedded.fields( + .field(category.name, is: .required, ofType: .string), + .field(category.color, is: .required, ofType: .embedded(type: Color.self)) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Color.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Color.swift index 793b6a6844..be00159e03 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Color.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Color.swift @@ -16,21 +16,23 @@ public struct Color: Embeddable { var blue: Int } -extension Color { - public enum CodingKeys: CodingKey { +public extension Color { + enum CodingKeys: CodingKey { case name case red case green case blue } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self - public static let schema = defineSchema { embedded in + static let schema = defineSchema { embedded in let color = Color.keys - embedded.fields(.field(color.name, is: .required, ofType: .string), - .field(color.red, is: .required, ofType: .int), - .field(color.green, is: .required, ofType: .int), - .field(color.blue, is: .required, ofType: .int)) + embedded.fields( + .field(color.name, is: .required, ofType: .string), + .field(color.red, is: .required, ofType: .int), + .field(color.green, is: .required, ofType: .int), + .field(color.blue, is: .required, ofType: .int) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicEmbedded.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicEmbedded.swift index 2636100012..dbe3743464 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicEmbedded.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicEmbedded.swift @@ -18,7 +18,7 @@ struct DynamicEmbedded: Embeddable, JSONValueHolder { public init(from decoder: Decoder) throws { let json = try JSONValue(from: decoder) if case .object(let jsonValue) = json { - values = jsonValue + self.values = jsonValue } else { self.values = [:] } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicModel.swift index a88cfeb7fe..c2207d7e1d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/DynamicModel.swift @@ -21,10 +21,10 @@ struct DynamicModel: Model, JSONValueHolder { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - id = try container.decode(String.self, forKey: .id) + self.id = try container.decode(String.self, forKey: .id) let json = try JSONValue(from: decoder) if case .object(let jsonValues) = json { - values = jsonValues + self.values = jsonValues } else { self.values = [:] } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Section.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Section.swift index 0ffd42eb2f..2686d17849 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Section.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Section.swift @@ -14,17 +14,19 @@ public struct Section: Embeddable { var number: Double } -extension Section { - public enum CodingKeys: CodingKey { +public extension Section { + enum CodingKeys: CodingKey { case name case number } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self - public static let schema = defineSchema { embedded in + static let schema = defineSchema { embedded in let section = Section.keys - embedded.fields(.field(section.name, is: .required, ofType: .string), - .field(section.number, is: .required, ofType: .double)) + embedded.fields( + .field(section.name, is: .required, ofType: .string), + .field(section.number, is: .required, ofType: .double) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo+Schema.swift index d53b4c0e07..75a2e93363 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Todo { +public extension Todo { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case description @@ -20,10 +20,10 @@ extension Todo { case stickies } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todo = Todo.keys model.listPluralName = "Todos" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo.swift index 423f2aa568..58eb250fcf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/NonModel/Todo.swift @@ -8,6 +8,7 @@ // swiftlint:disable all import Amplify import Foundation + /* The schema used to codegen this model: type Todo @model { @@ -45,12 +46,14 @@ public struct Todo: Model { public var section: Section? public var stickies: [String]? - public init(id: String = UUID().uuidString, - name: String, - description: String? = nil, - categories: [Category]? = [], - section: Section? = nil, - stickies: [String]? = []) { + public init( + id: String = UUID().uuidString, + name: String, + description: String? = nil, + categories: [Category]? = [], + section: Section? = nil, + stickies: [String]? = [] + ) { self.id = id self.name = name self.description = description diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost+Schema.swift index 69170decb4..9a31e531e8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension OGCScenarioBMGroupPost { +public extension OGCScenarioBMGroupPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case owner } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let oGCScenarioBMGroupPost = OGCScenarioBMGroupPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost.swift index 64ab04bf3f..7b07808b60 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBMGroupPost.swift @@ -14,9 +14,11 @@ public struct OGCScenarioBMGroupPost: Model { public var title: String public var owner: String? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - owner: String? = nil) { + owner: String? = nil + ) { self.id = id self.title = title self.owner = owner diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost+Schema.swift index 2a3c67066f..bf69f585ca 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension OGCScenarioBPost { +public extension OGCScenarioBPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case owner } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let oGCScenarioBPost = OGCScenarioBPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost.swift index 5ee8d97fb9..b49ef50072 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/OGCScenarioBPost.swift @@ -14,9 +14,11 @@ public struct OGCScenarioBPost: Model { public var title: String public var owner: String? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, - owner: String? = nil) { + owner: String? = nil + ) { self.id = id self.title = title self.owner = owner diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post+Schema.swift index 8ae2020779..51b399bccb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post { +public extension Post { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case content @@ -23,10 +23,10 @@ extension Post { case comments } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post = Post.keys model.listPluralName = "Posts" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post.swift index 282bd91846..7c43a79452 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Post.swift @@ -20,7 +20,8 @@ public struct Post: Model { public var status: PostStatus? public var comments: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, title: String, content: String, createdAt: Temporal.DateTime, @@ -28,7 +29,8 @@ public struct Post: Model { draft: Bool? = nil, rating: Double? = nil, status: PostStatus? = nil, - comments: List? = []) { + comments: List? = [] + ) { self.id = id self.title = title self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/PostCommentModelRegistration.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/PostCommentModelRegistration.swift index b3c1e7a4a1..b3e51e7f77 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/PostCommentModelRegistration.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/PostCommentModelRegistration.swift @@ -8,7 +8,7 @@ import Amplify import Foundation -final public class PostCommentModelRegistration: AmplifyModelRegistration { +public final class PostCommentModelRegistration: AmplifyModelRegistration { public func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post.self) ModelRegistry.register(modelType: Comment.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen+Schema.swift index 4571c1ed25..58ecadd569 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension QPredGen { +public extension QPredGen { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case myBool @@ -23,10 +23,10 @@ extension QPredGen { case myTime } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let qPredGen = QPredGen.keys model.listPluralName = "QPredGens" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen.swift index b26ad62ede..6c5f5e6406 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/QPredGen.swift @@ -8,6 +8,7 @@ // swiftlint:disable all import Amplify import Foundation + /* Generated from: @@ -34,7 +35,8 @@ public struct QPredGen: Model { public var myDateTime: Temporal.DateTime? public var myTime: Temporal.Time? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String, myBool: Bool? = nil, myDouble: Double? = nil, @@ -42,7 +44,8 @@ public struct QPredGen: Model { myString: String? = nil, myDate: Temporal.Date? = nil, myDateTime: Temporal.DateTime? = nil, - myTime: Temporal.Time? = nil) { + myTime: Temporal.Time? = nil + ) { self.id = id self.name = name self.myBool = myBool diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record+Schema.swift index 7df7ca922e..5d014387bf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record+Schema.swift @@ -5,13 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify + // swiftlint:disable all import Foundation -import Amplify -extension Record { +public extension Record { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case description @@ -21,10 +22,10 @@ extension Record { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let record = Record.keys model.listPluralName = "Records" @@ -41,10 +42,11 @@ extension Record { isReadOnly: true, ofType: RecordCover.self, associatedWith: RecordCover.keys.id, - targetName: "coverId"), + targetName: "coverId" + ), .field(record.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), .field(record.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) - ) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record.swift index 6b8f224c54..47608bb491 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Record.swift @@ -5,9 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify + // swiftlint:disable all import Foundation -import Amplify public struct Record: Model { public let id: String @@ -18,23 +19,29 @@ public struct Record: Model { public let createdAt: Temporal.DateTime? public let updatedAt: Temporal.DateTime? - public init(name: String, - description: String? = nil) { - self.init(name: name, - description: description, - coverId: nil, - cover: nil, - createdAt: nil, - updatedAt: nil) + public init( + name: String, + description: String? = nil + ) { + self.init( + name: name, + description: description, + coverId: nil, + cover: nil, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - description: String? = nil, - coverId: String? = nil, - cover: RecordCover? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + description: String? = nil, + coverId: String? = nil, + cover: RecordCover? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.description = description diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover+Schema.swift index 04f4f8a460..7b0fa29fcb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover+Schema.swift @@ -5,33 +5,34 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify + // swiftlint:disable all import Foundation -import Amplify -extension RecordCover { +public extension RecordCover { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case artist case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let recordCover = RecordCover.keys model.listPluralName = "RecordCovers" model.syncPluralName = "RecordCovers" model.fields( - .id(), - .field(recordCover.artist, is: .required, ofType: .string), - .field(recordCover.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), - .field(recordCover.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) - ) + .id(), + .field(recordCover.artist, is: .required, ofType: .string), + .field(recordCover.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime), + .field(recordCover.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover.swift index 21d00c458f..c3730c1d79 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/RecordCover.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation // swiftlint:disable all @@ -17,15 +17,19 @@ public struct RecordCover: Model { public let updatedAt: Temporal.DateTime? public init(artist: String) { - self.init(artist: artist, - createdAt: nil, - updatedAt: nil) + self.init( + artist: artist, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - artist: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + artist: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.artist = artist self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group+Schema.swift index e7a80ecd9b..9bbab7d799 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group+Schema.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation -extension Group { +public extension Group { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let group = Group.keys model.listPluralName = "Groups" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group.swift index 2a270048e6..5452511e2f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Group.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public struct Group: Model { public let id: String diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row+Schema.swift index 6878da26b5..3e55c96621 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row+Schema.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation -extension Row { +public extension Row { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case group } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let row = Row.keys model.listPluralName = "Rows" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row.swift index 496c3426e7..4db70b5d80 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Row.swift @@ -5,15 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public struct Row: Model { public let id: String public var group: Group - public init(id: String = UUID().uuidString, - group: Group) { + public init( + id: String = UUID().uuidString, + group: Group + ) { self.id = id self.group = group } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction+Schema.swift index 8c5ac3a9b0..4dc6dcfcfb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction+Schema.swift @@ -5,20 +5,21 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify + // swiftlint:disable all import Foundation -import Amplify -extension Transaction { +public extension Transaction { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let transaction = Transaction.keys model.listPluralName = "Transactions" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction.swift index 0cdd05cc3c..0c249b049a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ReservedWords/Transaction.swift @@ -5,9 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify + // swiftlint:disable all import Foundation -import Amplify public struct Transaction: Model { public let id: String diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish+Schema.swift index 3022b9e276..e8945e7e10 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Dish { +public extension Dish { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dishName case menu } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let dish = Dish.keys model.listPluralName = "Dishes" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish.swift index 73fe887fe0..58afa9e691 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Dish.swift @@ -14,9 +14,11 @@ public struct Dish: Model { public var dishName: String? public var menu: Menu? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, dishName: String? = nil, - menu: Menu? = nil) { + menu: Menu? = nil + ) { self.id = id self.dishName = dishName self.menu = menu diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu+Schema.swift index e3188b3f4f..34a3e35ceb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Menu { +public extension Menu { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case menuType @@ -19,10 +19,10 @@ extension Menu { case dishes } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let menu = Menu.keys model.listPluralName = "Menus" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu.swift index 5b571fef48..7ec55a7ec6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Menu.swift @@ -16,11 +16,13 @@ public struct Menu: Model { public var restaurant: Restaurant? public var dishes: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String, menuType: MenuType? = nil, restaurant: Restaurant? = nil, - dishes: List? = []) { + dishes: List? = [] + ) { self.id = id self.name = name self.menuType = menuType diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant+Schema.swift index 6d677b46aa..636f1d05ad 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Restaurant { +public extension Restaurant { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case restaurantName case menus } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let restaurant = Restaurant.keys model.listPluralName = "Restaurants" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant.swift index 37ce26d911..20ec8bde27 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Restaurant/Restaurant.swift @@ -14,9 +14,11 @@ public struct Restaurant: Model { public var restaurantName: String public var menus: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, restaurantName: String, - menus: List? = []) { + menus: List? = [] + ) { self.id = id self.restaurantName = restaurantName self.menus = menus diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel+Schema.swift index 05ff5b0fbc..bd9858f7d1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension EnumTestModel { +public extension EnumTestModel { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case enumVal case nullableEnumVal @@ -21,10 +21,10 @@ extension EnumTestModel { case nullableEnumNullableList } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let enumTestModel = EnumTestModel.keys model.listPluralName = "EnumTestModels" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel.swift index 65fe699440..ac3e7f73e3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/EnumTestModel.swift @@ -18,13 +18,15 @@ public struct EnumTestModel: Model { public var nullableEnumList: [TestEnum?] public var nullableEnumNullableList: [TestEnum?]? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, enumVal: TestEnum, nullableEnumVal: TestEnum? = nil, enumList: [TestEnum] = [], enumNullableList: [TestEnum]? = nil, nullableEnumList: [TestEnum?] = [], - nullableEnumNullableList: [TestEnum?]? = nil) { + nullableEnumNullableList: [TestEnum?]? = nil + ) { self.id = id self.enumVal = enumVal self.nullableEnumVal = nullableEnumVal diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer+Schema.swift index 6ef039ff38..8362ac98fe 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ListIntContainer { +public extension ListIntContainer { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case test case nullableInt @@ -21,10 +21,10 @@ extension ListIntContainer { case nullableIntNullableList } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let listIntContainer = ListIntContainer.keys model.listPluralName = "ListIntContainers" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer.swift index 4dd8862fe3..45604058ba 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListIntContainer.swift @@ -18,13 +18,15 @@ public struct ListIntContainer: Model { public var nullableIntList: [Int?] public var nullableIntNullableList: [Int?]? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, test: Int, nullableInt: Int? = nil, intList: [Int] = [], intNullableList: [Int]? = nil, nullableIntList: [Int?] = [], - nullableIntNullableList: [Int?]? = nil) { + nullableIntNullableList: [Int?]? = nil + ) { self.id = id self.test = test self.nullableInt = nullableInt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer+Schema.swift index 00d1f2b153..28095c5617 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ListStringContainer { +public extension ListStringContainer { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case test case nullableString @@ -21,10 +21,10 @@ extension ListStringContainer { case nullableStringNullableList } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let listStringContainer = ListStringContainer.keys model.listPluralName = "ListStringContainers" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer.swift index 5a23f7a5de..712c970012 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ListStringContainer.swift @@ -18,13 +18,15 @@ public struct ListStringContainer: Model { public var nullableStringList: [String?] public var nullableStringNullableList: [String?]? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, test: String, nullableString: String? = nil, stringList: [String] = [], stringNullableList: [String]? = nil, nullableStringList: [String?] = [], - nullableStringNullableList: [String?]? = nil) { + nullableStringNullableList: [String?]? = nil + ) { self.id = id self.test = test self.nullableString = nullableString diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Nested+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Nested+Schema.swift index f1d85adce4..edafe3cc62 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Nested+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Nested+Schema.swift @@ -9,17 +9,17 @@ import Amplify import Foundation -extension Nested { +public extension Nested { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case valueOne case valueTwo } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let nested = Nested.keys model.listPluralName = "Nesteds" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel+Schema.swift index 79f122f0ad..806dce775f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension NestedTypeTestModel { +public extension NestedTypeTestModel { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case nestedVal case nullableNestedVal @@ -21,10 +21,10 @@ extension NestedTypeTestModel { case nullableNestedNullableList } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let nestedTypeTestModel = NestedTypeTestModel.keys model.listPluralName = "NestedTypeTestModels" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel.swift index 5ceda72443..c9ba508760 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/NestedTypeTestModel.swift @@ -18,13 +18,15 @@ public struct NestedTypeTestModel: Model { public var nullableNestedList: [Nested?] public var nullableNestedNullableList: [Nested?]? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, nestedVal: Nested, nullableNestedVal: Nested? = nil, nestedList: [Nested] = [], nestedNullableList: [Nested]? = nil, nullableNestedList: [Nested?] = [], - nullableNestedNullableList: [Nested?]? = nil) { + nullableNestedNullableList: [Nested?]? = nil + ) { self.id = id self.nestedVal = nestedVal self.nullableNestedVal = nullableNestedVal diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Scalar+Equatable.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Scalar+Equatable.swift index 3dff2379d4..d8ddc691cc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Scalar+Equatable.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/Scalar+Equatable.swift @@ -7,7 +7,7 @@ extension ScalarContainer: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.myInt == rhs.myInt && lhs.myDouble == rhs.myDouble && lhs.myBool == rhs.myBool @@ -19,60 +19,60 @@ extension ScalarContainer: Equatable { && lhs.myJSON == rhs.myJSON && lhs.myPhone == rhs.myPhone && lhs.myURL == rhs.myURL - && lhs.myIPAddress == rhs.myIPAddress) + && lhs.myIPAddress == rhs.myIPAddress } } extension ListIntContainer: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.test == rhs.test && lhs.nullableInt == rhs.nullableInt && lhs.intList == rhs.intList && lhs.intNullableList == rhs.intNullableList && lhs.nullableIntList == rhs.nullableIntList - && lhs.nullableIntNullableList == rhs.nullableIntNullableList) + && lhs.nullableIntNullableList == rhs.nullableIntNullableList } } extension ListStringContainer: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.test == rhs.test && lhs.nullableString == rhs.nullableString && lhs.stringList == rhs.stringList && lhs.stringNullableList == rhs.stringNullableList && lhs.nullableStringList == rhs.nullableStringList - && lhs.nullableStringNullableList == rhs.nullableStringNullableList) + && lhs.nullableStringNullableList == rhs.nullableStringNullableList } } extension EnumTestModel: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.enumVal == rhs.enumVal && lhs.nullableEnumVal == rhs.nullableEnumVal && lhs.enumList == rhs.enumList && lhs.enumNullableList == rhs.enumNullableList && lhs.nullableEnumList == rhs.nullableEnumList - && lhs.nullableEnumNullableList == rhs.nullableEnumNullableList) + && lhs.nullableEnumNullableList == rhs.nullableEnumNullableList } } extension NestedTypeTestModel: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.id == rhs.id + return lhs.id == rhs.id && lhs.nestedVal == rhs.nestedVal && lhs.nullableNestedVal == rhs.nullableNestedVal && lhs.nestedList == rhs.nestedList && lhs.nestedNullableList == rhs.nestedNullableList && lhs.nullableNestedList == rhs.nullableNestedList - && lhs.nullableNestedNullableList == rhs.nullableNestedNullableList) + && lhs.nullableNestedNullableList == rhs.nullableNestedNullableList } } extension Nested: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { - return (lhs.valueOne == rhs.valueOne - && lhs.valueTwo == rhs.valueTwo) + return lhs.valueOne == rhs.valueOne + && lhs.valueTwo == rhs.valueTwo } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer+Schema.swift index 8fc935838a..d05931be73 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension ScalarContainer { +public extension ScalarContainer { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case myString case myInt @@ -28,10 +28,10 @@ extension ScalarContainer { case myIPAddress } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let scalarContainer = ScalarContainer.keys model.listPluralName = "ScalarContainers" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer.swift index 17191db613..94b6ff7475 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/Scalar/ScalarContainer.swift @@ -25,7 +25,8 @@ public struct ScalarContainer: Model { public var myURL: String? public var myIPAddress: String? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, myString: String? = nil, myInt: Int? = nil, myDouble: Double? = nil, @@ -38,7 +39,8 @@ public struct ScalarContainer: Model { myJSON: String? = nil, myPhone: String? = nil, myURL: String? = nil, - myIPAddress: String? = nil) { + myIPAddress: String? = nil + ) { self.id = id self.myString = myString self.myInt = myInt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post+Schema.swift index 57d9581507..cbc6d7ea57 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post+Schema.swift @@ -9,17 +9,17 @@ import Amplify import Foundation -extension ScenarioATest6Post { +public extension ScenarioATest6Post { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let scenarioATest6Post = ScenarioATest6Post.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post.swift index 108b4bfa0e..db203304ff 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/ScenarioATest6Post.swift @@ -13,8 +13,10 @@ public struct ScenarioATest6Post: Model { public let id: String public var title: String - public init(id: String = UUID().uuidString, - title: String) { + public init( + id: String = UUID().uuidString, + title: String + ) { self.id = id self.title = title } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project+Schema.swift index 73c9190fdc..1716d0b332 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension Project { +public extension Project { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project = Project.keys model.listPluralName = "Projects" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project.swift index 14ae5d0559..db3e85ced2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Project.swift @@ -14,9 +14,11 @@ public struct Project: Model { public var name: String? public var team: Team? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String? = nil, - team: Team? = nil) { + team: Team? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team+Schema.swift index a9710d86f8..d6dbe43e23 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team+Schema.swift @@ -9,17 +9,17 @@ import Amplify import Foundation -extension Team { +public extension Team { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team = Team.keys model.listPluralName = "Teams" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team.swift index 3ca4e7e2ef..086f20f10a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TeamProject/Team.swift @@ -13,8 +13,10 @@ public struct Team: Model { public let id: String public var name: String - public init(id: String = UUID().uuidString, - name: String) { + public init( + id: String = UUID().uuidString, + name: String + ) { self.id = id self.name = name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2+Schema.swift index e51bfa5402..f798199559 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project1V2 { +public extension Project1V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project1V2 { case project1V2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project1V2 = Project1V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2.swift index 34440bbb51..7cf9f9a23f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Project1V2.swift @@ -17,23 +17,29 @@ public struct Project1V2: Model { public var updatedAt: Temporal.DateTime? public var project1V2TeamId: String? - public init(id: String = UUID().uuidString, - name: String? = nil, - team: Team1V2? = nil, - project1V2TeamId: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team1V2? = nil, + project1V2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project1V2TeamId: project1V2TeamId) + project1V2TeamId: project1V2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team1V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project1V2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team1V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project1V2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2+Schema.swift index 8ed0f54ddf..2fa869b077 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Team1V2 { +public extension Team1V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team1V2 = Team1V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2.swift index ed29653b08..9e547cc972 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/1V2/Team1V2.swift @@ -15,17 +15,23 @@ public struct Team1V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2+Schema.swift index 286ca57848..b1d25f76ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project2V2 { +public extension Project2V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case teamID @@ -20,10 +20,10 @@ extension Project2V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project2V2 = Project2V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2.swift index fed160bd8c..adc2cfc7fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Project2V2.swift @@ -17,23 +17,29 @@ public struct Project2V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2V2? = nil + ) { + self.init( + id: id, name: name, teamID: teamID, team: team, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.teamID = teamID diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2+Schema.swift index 43e0f11b00..0db2c5e78b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Team2V2 { +public extension Team2V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team2V2 = Team2V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2.swift index 7f13b3927a..9b8e27a8b3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/2V2/Team2V2.swift @@ -15,17 +15,23 @@ public struct Team2V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2+Schema.swift index cee3850f92..023f2e2d90 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment3V2 { +public extension Comment3V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case postID case content @@ -19,10 +19,10 @@ extension Comment3V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment3V2 = Comment3V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2.swift index 52f14a06fe..6f0647dd70 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Comment3V2.swift @@ -16,20 +16,26 @@ public struct Comment3V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - postID: String, - content: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + postID: String, + content: String + ) { + self.init( + id: id, postID: postID, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - postID: String, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + postID: String, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.postID = postID self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2+Schema.swift index f377adf509..e8525efd3a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post3V2 { +public extension Post3V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post3V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post3V2 = Post3V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2.swift index 365ff8bc83..bfd3f9db93 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3V2/Post3V2.swift @@ -16,20 +16,26 @@ public struct Post3V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift index 41081acbfc..a2efc3dd3f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment3aV2 { +public extension Comment3aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt @@ -19,10 +19,10 @@ extension Comment3aV2 { case post3aV2CommentsId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment3aV2 = Comment3aV2.keys model.pluralName = "Comment3aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2.swift index 883bbd6eb8..362732db79 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Comment3aV2.swift @@ -16,20 +16,26 @@ public struct Comment3aV2: Model { public var updatedAt: Temporal.DateTime? public var post3aV2CommentsId: String? - public init(id: String = UUID().uuidString, - content: String, - post3aV2CommentsId: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + post3aV2CommentsId: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, updatedAt: nil, - post3aV2CommentsId: post3aV2CommentsId) + post3aV2CommentsId: post3aV2CommentsId + ) } - internal init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - post3aV2CommentsId: String? = nil) { + init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + post3aV2CommentsId: String? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift index 3b33c9960e..067713be06 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post3aV2 { +public extension Post3aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post3aV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post3aV2 = Post3aV2.keys model.pluralName = "Post3aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2.swift index 5332fcf81a..78361ec783 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/3aV2/Post3aV2.swift @@ -16,20 +16,26 @@ public struct Post3aV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2+Schema.swift index db568413b1..90683b5561 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment4V2 { +public extension Comment4V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment4V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment4V2 = Comment4V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2.swift index 5873d993e4..0d4073d6b4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Comment4V2.swift @@ -16,20 +16,26 @@ public struct Comment4V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2+Schema.swift index c0fa5fdfbb..e010e1c080 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post4V2 { +public extension Post4V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post4V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post4V2 = Post4V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2.swift index 7978edceb7..9106744759 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4V2/Post4V2.swift @@ -16,20 +16,26 @@ public struct Post4V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift index 5142fd05de..63cb47ada7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project4aV2 { +public extension Project4aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project4aV2 { case project4aV2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project4aV2 = Project4aV2.keys model.pluralName = "Project4aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2.swift index 51b873975c..4777b1dcda 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Project4aV2.swift @@ -21,23 +21,29 @@ public class Project4aV2: Model { public var updatedAt: Temporal.DateTime? public var project4aV2TeamId: String? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String? = nil, team: Team4aV2? = nil, - project4aV2TeamId: String? = nil) { - self.init(id: id, + project4aV2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project4aV2TeamId: project4aV2TeamId) + project4aV2TeamId: project4aV2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team4aV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project4aV2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team4aV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project4aV2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift index 9b7cae724e..18ccef180d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Team4aV2 { +public extension Team4aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case project @@ -19,10 +19,10 @@ extension Team4aV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team4aV2 = Team4aV2.keys model.pluralName = "Team4aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2.swift index 71d880f56b..7abfb7100b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4aV2/Team4aV2.swift @@ -16,20 +16,26 @@ public class Team4aV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String, - project: Project4aV2? = nil) { - self.init(id: id, + project: Project4aV2? = nil + ) { + self.init( + id: id, name: name, project: project, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - project: Project4aV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + project: Project4aV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.project = project diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift index 236d2be094..e3f4983c80 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project4bV2 { +public extension Project4bV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project4bV2 { case project4bV2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project4bV2 = Project4bV2.keys model.pluralName = "Project4bV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2.swift index 2369a6c57b..9b280c61df 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Project4bV2.swift @@ -17,23 +17,29 @@ public class Project4bV2: Model { public var updatedAt: Temporal.DateTime? public var project4bV2TeamId: String? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String? = nil, team: Team4bV2? = nil, - project4bV2TeamId: String? = nil) { - self.init(id: id, + project4bV2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project4bV2TeamId: project4bV2TeamId) + project4bV2TeamId: project4bV2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team4bV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project4bV2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team4bV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project4bV2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift index 311044fad2..eb0ec1c290 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Team4bV2 { +public extension Team4bV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case project @@ -19,10 +19,10 @@ extension Team4bV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team4bV2 = Team4bV2.keys model.pluralName = "Team4bV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2.swift index 644c856c81..b1831b611b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/4bV2/Team4bV2.swift @@ -16,20 +16,26 @@ public class Team4bV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String, - project: Project4bV2? = nil) { - self.init(id: id, + project: Project4bV2? = nil + ) { + self.init( + id: id, name: name, project: project, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - project: Project4bV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + project: Project4bV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.project = project diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2+Schema.swift index 84a32e2cb8..9528d2576d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post5V2 { +public extension Post5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case editors @@ -19,10 +19,10 @@ extension Post5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post5V2 = Post5V2.keys model.pluralName = "Post5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2.swift index 3165ee7f99..1090df258b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/Post5V2.swift @@ -16,20 +16,26 @@ public struct Post5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - editors: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + editors: List? = [] + ) { + self.init( + id: id, title: title, editors: editors, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - editors: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + editors: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.editors = editors diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift index cdbcd3e07d..23a7be5848 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension PostEditor5V2 { +public extension PostEditor5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post5V2 case user5V2 @@ -19,10 +19,10 @@ extension PostEditor5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let postEditor5V2 = PostEditor5V2.keys model.pluralName = "PostEditor5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2.swift index f78bbe9420..dabb434aac 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/PostEditor5V2.swift @@ -16,20 +16,26 @@ public struct PostEditor5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - post5V2: Post5V2, - user5V2: User5V2) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + post5V2: Post5V2, + user5V2: User5V2 + ) { + self.init( + id: id, post5V2: post5V2, user5V2: user5V2, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - post5V2: Post5V2, - user5V2: User5V2, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + post5V2: Post5V2, + user5V2: User5V2, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.post5V2 = post5V2 self.user5V2 = user5V2 diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2+Schema.swift index 5c35bd5ad9..a15d33b3ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension User5V2 { +public extension User5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case username case posts @@ -19,10 +19,10 @@ extension User5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let user5V2 = User5V2.keys model.pluralName = "User5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2.swift index 7329a37803..dbf049a0f0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/5V2/User5V2.swift @@ -16,20 +16,26 @@ public struct User5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - username: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + username: String, + posts: List? = [] + ) { + self.init( + id: id, username: username, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - username: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + username: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.username = username self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2+Schema.swift index 0c2d801a88..280cafde47 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog6V2 { +public extension Blog6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts @@ -19,10 +19,10 @@ extension Blog6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog6V2 = Blog6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2.swift index 1d1c62c34c..b4cbf30247 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Blog6V2.swift @@ -16,20 +16,26 @@ public struct Blog6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2+Schema.swift index 2d8fe7959c..cb476aa8cc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment6V2 { +public extension Comment6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post case content @@ -19,10 +19,10 @@ extension Comment6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment6V2 = Comment6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2.swift index f975f70fb2..027da3fbc5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Comment6V2.swift @@ -16,20 +16,26 @@ public struct Comment6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - post: Post6V2? = nil, - content: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + post: Post6V2? = nil, + content: String + ) { + self.init( + id: id, post: post, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - post: Post6V2? = nil, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + post: Post6V2? = nil, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.post = post self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2+Schema.swift index 5e96bf8cd9..8322b709e5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post6V2 { +public extension Post6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case blog @@ -20,10 +20,10 @@ extension Post6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post6V2 = Post6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2.swift index bebe11af46..c955a6e87e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/6V2/Post6V2.swift @@ -17,23 +17,29 @@ public struct Post6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - blog: Blog6V2? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + blog: Blog6V2? = nil, + comments: List? = [] + ) { + self.init( + id: id, title: title, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - blog: Blog6V2? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + blog: Blog6V2? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.blog = blog diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2+Schema.swift index 84fa41ace3..5e2f6f64ca 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog7V2 { +public extension Blog7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts @@ -19,10 +19,10 @@ extension Blog7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog7V2 = Blog7V2.keys model.pluralName = "Blog7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2.swift index e963392ee5..537cd210a4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Blog7V2.swift @@ -16,20 +16,26 @@ public struct Blog7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2+Schema.swift index 0f71ceb037..077286678f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment7V2 { +public extension Comment7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment7V2 = Comment7V2.keys model.pluralName = "Comment7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2.swift index 317bef7b62..fa9b8c14ec 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Comment7V2.swift @@ -16,20 +16,26 @@ public struct Comment7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post7V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post7V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post7V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post7V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2+Schema.swift index e16552145c..18d5da8dc9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post7V2 { +public extension Post7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case blog @@ -20,10 +20,10 @@ extension Post7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post7V2 = Post7V2.keys model.pluralName = "Post7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2.swift index a1cb3dfb84..e6fe9a9aab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/7V2/Post7V2.swift @@ -17,23 +17,29 @@ public struct Post7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - blog: Blog7V2? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + blog: Blog7V2? = nil, + comments: List? = [] + ) { + self.init( + id: id, title: title, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - blog: Blog7V2? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + blog: Blog7V2? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.blog = blog diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift index d77a61d5ee..aa10f9edd5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Attendee8V2 { +public extension Attendee8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case meetings case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let attendee8V2 = Attendee8V2.keys model.pluralName = "Attendee8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2.swift index bdb90d7726..1ae9221f59 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Attendee8V2.swift @@ -15,17 +15,23 @@ public struct Attendee8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - meetings: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + meetings: List? = [] + ) { + self.init( + id: id, meetings: meetings, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - meetings: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + meetings: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.meetings = meetings self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift index ea734e16d1..540f9e81b7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Meeting8V2 { +public extension Meeting8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case attendees @@ -19,10 +19,10 @@ extension Meeting8V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let meeting8V2 = Meeting8V2.keys model.pluralName = "Meeting8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2.swift index 84abbbdd0c..8101985510 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Meeting8V2.swift @@ -16,20 +16,26 @@ public struct Meeting8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - attendees: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + attendees: List? = [] + ) { + self.init( + id: id, title: title, attendees: attendees, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - attendees: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + attendees: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.attendees = attendees diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2+Schema.swift index 72355ba4ea..303c84d91b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Registration8V2 { +public extension Registration8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case meeting case attendee @@ -19,10 +19,10 @@ extension Registration8V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let registration8V2 = Registration8V2.keys model.pluralName = "Registration8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2.swift index f9d2aa3b4b..3c572b4969 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/8V2/Registration8V2.swift @@ -16,20 +16,26 @@ public struct Registration8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - meeting: Meeting8V2, - attendee: Attendee8V2) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + meeting: Meeting8V2, + attendee: Attendee8V2 + ) { + self.init( + id: id, meeting: meeting, attendee: attendee, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - meeting: Meeting8V2, - attendee: Attendee8V2, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + meeting: Meeting8V2, + attendee: Attendee8V2, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.meeting = meeting self.attendee = attendee diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift index f760ef2c9c..fae219e308 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerMultipleSecondaryIndexV2 { +public extension CustomerMultipleSecondaryIndexV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case phoneNumber @@ -21,10 +21,10 @@ extension CustomerMultipleSecondaryIndexV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerMultipleSecondaryIndexV2 = CustomerMultipleSecondaryIndexV2.keys model.pluralName = "CustomerMultipleSecondaryIndexV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift index 7e92f12052..1c4e60e2d5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift @@ -18,26 +18,32 @@ public struct CustomerMultipleSecondaryIndexV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - age: Int, - accountRepresentativeID: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + age: Int, + accountRepresentativeID: String + ) { + self.init( + id: id, name: name, phoneNumber: phoneNumber, age: age, accountRepresentativeID: accountRepresentativeID, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - age: Int, - accountRepresentativeID: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + age: Int, + accountRepresentativeID: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.phoneNumber = phoneNumber diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift index 3058f7d566..1118ef8ca6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerSecondaryIndexV2 { +public extension CustomerSecondaryIndexV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case phoneNumber @@ -20,10 +20,10 @@ extension CustomerSecondaryIndexV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerSecondaryIndexV2 = CustomerSecondaryIndexV2.keys model.pluralName = "CustomerSecondaryIndexV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2.swift index e6e0d76c04..195405ac60 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerSecondaryIndexV2.swift @@ -17,23 +17,29 @@ public struct CustomerSecondaryIndexV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - accountRepresentativeID: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + accountRepresentativeID: String + ) { + self.init( + id: id, name: name, phoneNumber: phoneNumber, accountRepresentativeID: accountRepresentativeID, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - accountRepresentativeID: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + accountRepresentativeID: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.phoneNumber = phoneNumber diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift index 40e8c0f7ce..021d8bfa84 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerWithMultipleFieldsinPK { +public extension CustomerWithMultipleFieldsinPK { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dob case date @@ -25,10 +25,10 @@ extension CustomerWithMultipleFieldsinPK { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerWithMultipleFieldsinPK = CustomerWithMultipleFieldsinPK.keys model.pluralName = "CustomerWithMultipleFieldsinPKs" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift index 32293d9975..0ae721e741 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift @@ -22,16 +22,19 @@ public struct CustomerWithMultipleFieldsinPK: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - date: Temporal.Date, - time: Temporal.Time, - phoneNumber: Int, - priority: Priority, - height: Double, - firstName: String? = nil, - lastName: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + date: Temporal.Date, + time: Temporal.Time, + phoneNumber: Int, + priority: Priority, + height: Double, + firstName: String? = nil, + lastName: String? = nil + ) { + self.init( + id: id, dob: dob, date: date, time: time, @@ -41,19 +44,22 @@ public struct CustomerWithMultipleFieldsinPK: Model { firstName: firstName, lastName: lastName, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - date: Temporal.Date, - time: Temporal.Time, - phoneNumber: Int, - priority: Priority, - height: Double, - firstName: String? = nil, - lastName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + date: Temporal.Date, + time: Temporal.Time, + phoneNumber: Int, + priority: Priority, + height: Double, + firstName: String? = nil, + lastName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.date = date diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift index 03ace0efac..9f21d12e70 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog8 { +public extension Blog8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case customs @@ -21,10 +21,10 @@ extension Blog8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog8 = Blog8.keys model.pluralName = "Blog8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8.swift index 92c1ccae48..48aa59e7fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Blog8.swift @@ -18,26 +18,32 @@ public struct Blog8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [] + ) { + self.init( + id: id, name: name, customs: customs, notes: notes, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.customs = customs diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift index 6258c76ca6..f2e773e8ee 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment8 { +public extension Comment8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment8 = Comment8.keys model.pluralName = "Comment8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8.swift index 4a0042140e..d6fa843ba3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Comment8.swift @@ -16,20 +16,26 @@ public struct Comment8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift index 27f611af59..85693fb8fa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension MyCustomModel8 { +public extension MyCustomModel8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case desc case children } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let myCustomModel8 = MyCustomModel8.keys model.pluralName = "MyCustomModel8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift index 1d18ede96f..206fee3987 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension MyNestedModel8 { +public extension MyNestedModel8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case nestedName case notes } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let myNestedModel8 = MyNestedModel8.keys model.pluralName = "MyNestedModel8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift index bd21917eb4..5cf1fb9e29 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post8 { +public extension Post8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case randomId @@ -21,10 +21,10 @@ extension Post8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post8 = Post8.keys model.pluralName = "Post8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8.swift index 306eb3395b..09bec3b160 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/OptionalAssociations/Post8.swift @@ -18,26 +18,32 @@ public struct Post8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8? = nil, + comments: List? = [] + ) { + self.init( + id: id, name: name, randomId: randomId, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.randomId = randomId diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift index 5d527c5bdf..59af4deb74 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension SchemaDrift { +public extension SchemaDrift { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case enumValue case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let schemaDrift = SchemaDrift.keys model.pluralName = "SchemaDrifts" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift index dfac48fda6..b6159e7589 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift @@ -30,17 +30,23 @@ public struct SchemaDrift: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - enumValue: EnumDrift? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + enumValue: EnumDrift? = nil + ) { + self.init( + id: id, enumValue: enumValue, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - enumValue: EnumDrift? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + enumValue: EnumDrift? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.enumValue = enumValue self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift index 716f4848fe..2ed40a52b9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension TodoCustomTimestampV2 { +public extension TodoCustomTimestampV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdOn case updatedOn } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoCustomTimestampV2 = TodoCustomTimestampV2.keys model.pluralName = "TodoCustomTimestampV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2.swift index 4bad844e17..97842a31a0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoCustomTimestampV2.swift @@ -15,17 +15,23 @@ public struct TodoCustomTimestampV2: Model { public var createdOn: Temporal.DateTime? public var updatedOn: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdOn: nil, - updatedOn: nil) + updatedOn: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdOn: Temporal.DateTime? = nil, - updatedOn: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdOn: Temporal.DateTime? = nil, + updatedOn: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdOn = createdOn diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift index 6de5d45ae2..0e390adf51 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension TodoWithDefaultValueV2 { +public extension TodoWithDefaultValueV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoWithDefaultValueV2 = TodoWithDefaultValueV2.keys model.pluralName = "TodoWithDefaultValueV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2.swift index dd622e15fc..75c66e59c2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/TransformerV2/TodoWithDefaultValueV2.swift @@ -15,17 +15,23 @@ public struct TodoWithDefaultValueV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User+Schema.swift index 7e59a9d0a7..45eed23650 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension User { +public extension User { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case following case followers } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let user = User.keys model.listPluralName = "Users" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User.swift index e3bf9a2bb1..cd852353ea 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/User.swift @@ -15,10 +15,12 @@ public struct User: Model { public var following: List? public var followers: List? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, name: String, following: List? = [], - followers: List? = []) { + followers: List? = [] + ) { self.id = id self.name = name self.following = following diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers+Schema.swift index 61de3ccd2a..657a4f854e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension UserFollowers { +public extension UserFollowers { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case user case followersUser } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let userFollowers = UserFollowers.keys model.listPluralName = "UserFollowers" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers.swift index 5c2f851f90..ccbc4f0e10 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowers.swift @@ -14,9 +14,11 @@ public struct UserFollowers: Model { public var user: User? public var followersUser: User? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, user: User? = nil, - followersUser: User? = nil) { + followersUser: User? = nil + ) { self.id = id self.user = user self.followersUser = followersUser diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing+Schema.swift index d3dec6d064..4788315076 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension UserFollowing { +public extension UserFollowing { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case user case followingUser } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let userFollowing = UserFollowing.keys model.listPluralName = "UserFollowings" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing.swift index a545803ac3..cc61a04a54 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/Models/UserFollowing.swift @@ -14,9 +14,11 @@ public struct UserFollowing: Model { public var user: User? public var followingUser: User? - public init(id: String = UUID().uuidString, + public init( + id: String = UUID().uuidString, user: User? = nil, - followingUser: User? = nil) { + followingUser: User? = nil + ) { self.id = id self.user = user self.followingUser = followingUser diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/SubscriptionEndToEndTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/SubscriptionEndToEndTests.swift index 3642428f98..34436cc5f7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/SubscriptionEndToEndTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/SubscriptionEndToEndTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Combine import AWSPluginsCore +import Combine +import XCTest @testable import Amplify @testable import AWSDataStorePlugin @@ -77,7 +77,7 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { XCTAssertEqual(createdPost?.content, originalContent) XCTAssertEqual(createSyncData?.syncMetadata.version, 1) XCTAssertEqual(createSyncData?.syncMetadata.deleted, false) - + // Act: send update mutation try await sendUpdateRequest(forId: id, content: updatedContent, version: 1) await fulfillment(of: [updateReceived], timeout: 10) @@ -89,7 +89,7 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { XCTAssertEqual(updatedPost?.content, updatedContent) XCTAssertEqual(updateSyncData?.syncMetadata.version, 2) XCTAssertEqual(updateSyncData?.syncMetadata.deleted, false) - + // Act: send delete mutation try await sendDeleteRequest(forId: id, version: 2) await fulfillment(of: [deleteReceived], timeout: 10) @@ -108,7 +108,8 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { title updatedAt __typename _version _deleted _lastChangedAt } } """ - let input: [String: Any] = ["input": + let input: [String: Any] = [ + "input": [ "id": id, "title": Optional("This is a new post I created"), @@ -120,10 +121,12 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { ] ] - let request = GraphQLRequest(document: document, - variables: input, - responseType: Post.self, - decodePath: "createPost") + let request = GraphQLRequest( + document: document, + variables: input, + responseType: Post.self, + decodePath: "createPost" + ) let graphQLResult = try await Amplify.API.mutate(request: request) switch graphQLResult { @@ -142,7 +145,8 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { title updatedAt __typename _version _deleted _lastChangedAt } } """ - let input: [String: Any] = ["input": + let input: [String: Any] = [ + "input": [ "id": id, "content": content, @@ -150,10 +154,12 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { ] ] - let request = GraphQLRequest(document: document, - variables: input, - responseType: Post.self, - decodePath: "updatePost") + let request = GraphQLRequest( + document: document, + variables: input, + responseType: Post.self, + decodePath: "updatePost" + ) let graphQLResult = try await Amplify.API.mutate(request: request) switch graphQLResult { @@ -172,17 +178,20 @@ class SubscriptionEndToEndTests: SyncEngineIntegrationTestBase { title updatedAt __typename _version _deleted _lastChangedAt } } """ - let input: [String: Any] = ["input": + let input: [String: Any] = [ + "input": [ "id": id, "_version": version ] ] - let request = GraphQLRequest(document: document, - variables: input, - responseType: Post.self, - decodePath: "deletePost") + let request = GraphQLRequest( + document: document, + variables: input, + responseType: Post.self, + decodePath: "deletePost" + ) let graphQLResult = try await Amplify.API.mutate(request: request) switch graphQLResult { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreInternal.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreInternal.swift index 84e7fb7f9b..beae3433c0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreInternal.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreInternal.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import Foundation @testable import Amplify @testable import AWSDataStorePlugin -import Foundation -struct DataStoreInternal { +enum DataStoreInternal { static var dbFilePath: URL? { getAdapter()?.dbFilePath } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreTestBase.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreTestBase.swift index af43355440..c59161451e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/DataStoreTestBase.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import XCTest -import Amplify class DataStoreTestBase: XCTestCase { - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/SyncEngineIntegrationTestBase.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/SyncEngineIntegrationTestBase.swift index 33be2c76f0..846f847f06 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/SyncEngineIntegrationTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/TestSupport/SyncEngineIntegrationTestBase.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Combine import AWSAPIPlugin +import Combine +import XCTest @testable import Amplify @testable import AWSDataStorePlugin @@ -79,11 +79,11 @@ class SyncEngineIntegrationTestBase: DataStoreTestBase { return } } - + func stopDataStore() async throws { try await Amplify.DataStore.stop() } - + func clearDataStore() async throws { try await Amplify.DataStore.clear() } @@ -125,5 +125,5 @@ class SyncEngineIntegrationTestBase: DataStoreTestBase { await fulfillment(of: [eventReceived], timeout: 10) } - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/AWSDataStoreLazyLoadPostComment4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/AWSDataStoreLazyLoadPostComment4V2.swift index 9a315baed5..aefb9f3ed7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/AWSDataStoreLazyLoadPostComment4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/AWSDataStoreLazyLoadPostComment4V2.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @@ -17,7 +17,7 @@ class AWSDataStoreLazyLoadPostComment4V2: AWSDataStoreLazyLoadBaseTest { await setup(withModels: PostComment4V2Models()) let post = Post4V2(title: "title") let comment = Comment4V2(content: "content", post: post) - + let commentSynced = expectation(description: "DataStore start success") let mutationEvents = Amplify.DataStore.observe(Comment4V2.self) Task { @@ -31,10 +31,10 @@ class AWSDataStoreLazyLoadPostComment4V2: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed with error \(error)") } } - + try await Amplify.DataStore.save(post) try await Amplify.DataStore.save(comment) - + await fulfillment(of: [commentSynced], timeout: 10) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2SnapshotTests.swift index b7b294b081..f08dcd0bc8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2SnapshotTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostComment4V2Tests { - + func testPostSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment4V2Models()) continueAfterFailure = true @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -148,13 +148,13 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment4V2Models()) continueAfterFailure = true let post = Post(title: "title") let comment = Comment(content: "content", post: post) - + // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -182,7 +182,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -210,7 +210,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -238,7 +238,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -261,7 +261,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -284,7 +284,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -307,7 +307,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ @@ -335,5 +335,5 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2StressTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2StressTests.swift index 260534710f..30e8aee057 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2StressTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/AWSDataStoreLazyLoadPostComment4V2StressTests.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest import Amplify -import AWSPluginsCore import AWSDataStorePlugin +import AWSPluginsCore extension AWSDataStoreLazyLoadPostComment4V2Tests { static let loggingContext = "multiSaveWithInterruptions" - /// Test performing save's and stop/start concurrently. + /// Test performing save's and stop/start concurrently. /// /// This test was validated prior to [PR 3492](https://github.com/aws-amplify/amplify-swift/pull/3492) /// and will fail. The failure will show up when the test asserts that a queried comment from AppSync should contain the associated @@ -63,7 +63,7 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { /// The minimum number of iterations, through trial and error, found to reproduce the bug. private let count = 15 - + /// `isOutboxEmpty` is used to return the flow back to the caller via fulfilling the `savesSyncedExpectation`. /// By listening to the OutboxEvent after performing the operations, the last outboxEvent to be `true` while `index` /// is the last index, will be when `savesSyncedExpectation` is fulfilled and returned execution back to the caller. @@ -82,10 +82,10 @@ extension AWSDataStoreLazyLoadPostComment4V2Tests { while isOutboxEmpty == false { try await Task.sleep(seconds: 1) } - for i in 0...createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: PostComment4V2Models()) try await startAndWaitForReady() @@ -289,18 +319,18 @@ class AWSDataStoreLazyLoadPostComment4V2Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostComment4V2Models()) try await startAndWaitForReady() @@ -322,27 +352,27 @@ class AWSDataStoreLazyLoadPostComment4V2Tests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + snapshotReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: PostComment4V2Models()) try await startAndWaitForReady() - + let post = Post(title: "title") let savedPost = try await createAndWaitForSync(post) let comment = Comment(content: "content", post: post) @@ -356,14 +386,14 @@ class AWSDataStoreLazyLoadPostComment4V2Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -372,7 +402,7 @@ class AWSDataStoreLazyLoadPostComment4V2Tests: AWSDataStoreLazyLoadBaseTest { extension AWSDataStoreLazyLoadPostComment4V2Tests { typealias Post = Post4V2 typealias Comment = Comment4V2 - + struct PostComment4V2Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2+Schema.swift index 225bbfd4fd..448c925ca0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2+Schema.swift @@ -1,34 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4V2 { +public extension Comment4V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let comment4V2 = Comment4V2.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Comment4V2s" - + model.attributes( .index(fields: ["postID", "content"], name: "byPost4"), .primaryKey(fields: [comment4V2.id]) ) - + model.fields( .field(comment4V2.id, is: .required, ofType: .string), .field(comment4V2.content, is: .required, ofType: .string), @@ -37,29 +44,29 @@ extension Comment4V2 { .field(comment4V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment4V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Comment4V2 { - public var id: FieldPath { +public extension ModelPath where ModelType == Comment4V2 { + var id: FieldPath { string("id") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var post: ModelPath { + var post: ModelPath { Post4V2.Path(name: "post", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2.swift index fe39f08abe..ee184a16d7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Comment4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Comment4V2: Model { public let id: String public var content: String - internal var _post: LazyReference + var _post: LazyReference public var post: Post4V2? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct Comment4V2: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil) { - self.init(id: id, - content: content, - post: post, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil + ) { + self.init( + id: id, + content: content, + post: post, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct Comment4V2: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post4V2? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try values.decode(String.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try values.decode(String.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2+Schema.swift index 3caa6ac8cd..9f73e2b710 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4V2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post4V2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post4V2 = Post4V2.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Post4V2s" - + model.attributes( .primaryKey(fields: [post4V2.id]) ) - + model.fields( .field(post4V2.id, is: .required, ofType: .string), .field(post4V2.title, is: .required, ofType: .string), @@ -36,10 +43,10 @@ extension Post4V2 { .field(post4V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post4V2: ModelIdentifiable { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2.swift index 08f3e4b429..9106744759 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL1/Post4V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4V2: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7SnapshotTests.swift index a136207c79..a014bcd7b1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7SnapshotTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostComment7Tests { @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -148,14 +148,16 @@ extension AWSDataStoreLazyLoadPostComment7Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment7Models()) continueAfterFailure = true let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post: post) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post: post + ) // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -183,7 +185,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -211,7 +213,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -239,7 +241,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -263,7 +265,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -287,7 +289,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -311,7 +313,7 @@ extension AWSDataStoreLazyLoadPostComment7Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7Tests.swift index 89462e259c..3e30afd2ce 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/AWSDataStoreLazyLoadPostComment7Tests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest { @@ -19,7 +19,7 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let post = Post(postId: UUID().uuidString, title: "title") try await createAndWaitForSync(post) } - + func testSaveComment() async throws { await setup(withModels: PostComment7Models()) try await startAndWaitForReady() @@ -28,10 +28,10 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) } - + func testLazyLoad() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) let savedPost = try await createAndWaitForSync(post) @@ -43,73 +43,91 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let queriedPost = try await query(for: savedPost) try await assertPost(queriedPost, canLazyLoad: savedComment) } - - func assertComment(_ comment: Comment, - hasEagerLoaded post: Post) async throws { - assertLazyReference(comment._post, - state: .loaded(model: post)) - + + func assertComment( + _ comment: Comment, + hasEagerLoaded post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) + guard let loadedPost = try await comment.post else { XCTFail("Failed to retrieve the post from the comment") return } XCTAssertEqual(loadedPost.postId, post.postId) - + // retrieve loaded model guard let loadedPost = try await comment.post else { XCTFail("Failed to retrieve the loaded post from the comment") return } XCTAssertEqual(loadedPost.postId, post.postId) - + try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertComment(_ comment: Comment, - canLazyLoad post: Post) async throws { - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [ - .init(name: Post7.keys.postId.stringValue, value: post.postId), - .init(name: Post7.keys.title.stringValue, value: post.title) - ])) + + func assertComment( + _ comment: Comment, + canLazyLoad post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [ + .init(name: Post7.keys.postId.stringValue, value: post.postId), + .init(name: Post7.keys.title.stringValue, value: post.title) + ]) + ) guard let loadedPost = try await comment.post else { XCTFail("Failed to load the post from the comment") return } XCTAssertEqual(loadedPost.postId, post.postId) - assertLazyReference(comment._post, - state: .loaded(model: post)) + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIds: [post.identifier], - associatedFields: ["post"])) + assertList(comments, state: .isNotLoaded( + associatedIds: [post.identifier], + associatedFields: ["post"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { XCTFail("Missing lazy loaded comment from post") return } - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [ - .init(name: Post7.keys.postId.stringValue, value: post.postId), - .init(name: Post7.keys.title.stringValue, value: post.title) - ])) + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [ + .init(name: Post7.keys.postId.stringValue, value: post.postId), + .init(name: Post7.keys.title.stringValue, value: post.title) + ]) + ) } - + func testSaveWithoutPost() async throws { await setup(withModels: PostComment7Models()) let comment = Comment(commentId: UUID().uuidString, content: "content") let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: nil) + ) let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) queriedComment.setPost(savedPost) @@ -117,7 +135,7 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithPost) try await assertComment(queriedComment2, canLazyLoad: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: PostComment7Models()) let post = Post(postId: UUID().uuidString, title: "title") @@ -125,30 +143,34 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) let queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.postId.stringValue, value: post.postId), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.postId.stringValue, value: post.postId), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) let savedQueriedComment = try await updateAndWaitForSync(queriedComment) let queriedComment2 = try await query(for: savedQueriedComment) try await assertComment(queriedComment2, canLazyLoad: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.postId.stringValue, value: post.postId), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.postId.stringValue, value: post.postId), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) + let newPost = Post(postId: UUID().uuidString, title: "title") _ = try await createAndWaitForSync(newPost) queriedComment.setPost(newPost) @@ -156,31 +178,35 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithNewPost) try await assertComment(queriedComment2, canLazyLoad: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.postId.stringValue, value: post.postId), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.postId.stringValue, value: post.postId), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) + queriedComment.setPost(nil) let saveCommentRemovePost = try await updateAndWaitForSync(queriedComment) let queriedCommentNoPost = try await query(for: saveCommentRemovePost) - assertLazyReference(queriedCommentNoPost._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedCommentNoPost._post, + state: .notLoaded(identifiers: nil) + ) } - + func testDelete() async throws { await setup(withModels: PostComment7Models()) - + let post = Post(postId: UUID().uuidString, title: "title") let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) let savedPost = try await createAndWaitForSync(post) @@ -189,7 +215,7 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest try await assertModelDoesNotExist(savedComment) try await assertModelDoesNotExist(savedPost) } - + func testObservePost() async throws { await setup(withModels: PostComment7Models()) try await startAndWaitForReady() @@ -203,7 +229,7 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest version == 1, let receivedPost = try? mutationEvent.decodeModel(as: Post.self), receivedPost.postId == post.postId { - + try await createAndWaitForSync(comment) guard let comments = receivedPost.comments else { XCTFail("Lazy List does not exist") @@ -215,23 +241,23 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: PostComment7Models()) try await startAndWaitForReady() @@ -251,18 +277,18 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostComment7Models()) try await startAndWaitForReady() @@ -284,27 +310,27 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + snapshotReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: PostComment7Models()) try await startAndWaitForReady() - + let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) let comment = Comment(commentId: UUID().uuidString, content: "content", post: post) @@ -318,14 +344,14 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -334,7 +360,7 @@ final class AWSDataStoreLazyLoadPostComment7Tests: AWSDataStoreLazyLoadBaseTest extension AWSDataStoreLazyLoadPostComment7Tests { typealias Post = Post7 typealias Comment = Comment7 - + struct PostComment7Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7+Schema.swift index 2850d94c8d..1cb4ae68a7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment7 { +public extension Comment7 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case commentId case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let comment7 = Comment7.keys - + model.pluralName = "Comment7s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .index(fields: ["postId", "postTitle"], name: "byPost"), .primaryKey(fields: [comment7.commentId, comment7.content]) ) - + model.fields( .field(comment7.commentId, is: .required, ofType: .string), .field(comment7.content, is: .required, ofType: .string), @@ -34,9 +41,9 @@ extension Comment7 { .field(comment7.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment7: ModelIdentifiable { @@ -44,26 +51,28 @@ extension Comment7: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment7.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment7.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == Comment7 { - public var commentId: FieldPath { +public extension ModelPath where ModelType == Comment7 { + var commentId: FieldPath { string("commentId") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var post: ModelPath { + var post: ModelPath { Post7.Path(name: "post", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7.swift index ff1a8abfae..dd9775521a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Comment7.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Comment7: Model { public let commentId: String public let content: String - internal var _post: LazyReference + var _post: LazyReference public var post: Post7? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct Comment7: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - content: String, - post: Post7? = nil) { - self.init(commentId: commentId, - content: content, - post: post, - createdAt: nil, - updatedAt: nil) + + public init( + commentId: String, + content: String, + post: Post7? = nil + ) { + self.init( + commentId: commentId, + content: content, + post: post, + createdAt: nil, + updatedAt: nil + ) } - internal init(commentId: String, - content: String, - post: Post7? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + content: String, + post: Post7? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct Comment7: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post7? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - commentId = try values.decode(String.self, forKey: .commentId) - content = try values.decode(String.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.commentId = try values.decode(String.self, forKey: .commentId) + self.content = try values.decode(String.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7+Schema.swift index 2a1cf86992..a110e8378b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post7 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post7 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post7 = Post7.keys - + model.pluralName = "Post7s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post7.postId, post7.title]) ) - + model.fields( .field(post7.postId, is: .required, ofType: .string), .field(post7.title, is: .required, ofType: .string), @@ -33,10 +40,10 @@ extension Post7 { .field(post7.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post7: ModelIdentifiable { @@ -44,10 +51,12 @@ extension Post7: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post7.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post7.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7.swift index 8cb750a96d..c07fbc8320 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL10/Post7.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post7: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8SnapshotTests.swift index ae70c2d65f..e4c629cc1f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8SnapshotTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostComment8Tests { @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -148,15 +148,17 @@ extension AWSDataStoreLazyLoadPostComment8Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment8Models()) continueAfterFailure = true let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -176,7 +178,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -196,7 +198,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -216,7 +218,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -236,7 +238,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -256,7 +258,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -276,7 +278,7 @@ extension AWSDataStoreLazyLoadPostComment8Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8Tests.swift index a6375821d1..ed9d26bfe1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/AWSDataStoreLazyLoadPostComment8Tests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest { @@ -19,27 +19,31 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest let post = Post(postId: UUID().uuidString, title: "title") try await createAndWaitForSync(post) } - + func testSaveComment() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) try await createAndWaitForSync(post) try await createAndWaitForSync(comment) } - + func testLazyLoad() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) assertComment(savedComment, contains: savedPost) @@ -49,25 +53,29 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest let queriedPost = try await query(for: savedPost) try await assertPost(queriedPost, canLazyLoad: savedComment) } - + func assertComment(_ comment: Comment, contains post: Post) { XCTAssertEqual(comment.postId, post.postId) XCTAssertEqual(comment.postTitle, post.title) } - + func assertCommentDoesNotContainPost(_ comment: Comment) { XCTAssertNil(comment.postId) XCTAssertNil(comment.postTitle) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIds: [post.postId, post.title], - associatedFields: ["postId", "postTitle"])) + assertList(comments, state: .isNotLoaded( + associatedIds: [post.postId, post.title], + associatedFields: ["postId", "postTitle"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { @@ -76,7 +84,7 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest } assertComment(comment, contains: post) } - + func testSaveWithoutPost() async throws { await setup(withModels: PostComment8Models()) let comment = Comment(commentId: UUID().uuidString, content: "content") @@ -91,14 +99,16 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithPost) assertComment(queriedComment2, contains: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: PostComment8Models()) let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) let queriedComment = try await query(for: savedComment) @@ -107,15 +117,17 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: savedQueriedComment) assertComment(queriedComment2, contains: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) @@ -128,55 +140,61 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithNewPost) assertComment(queriedComment2, contains: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) assertComment(queriedComment, contains: post) - + queriedComment.postId = nil queriedComment.postTitle = nil - + let saveCommentRemovePost = try await updateAndWaitForSync(queriedComment) let queriedCommentNoPost = try await query(for: saveCommentRemovePost) assertCommentDoesNotContainPost(queriedCommentNoPost) } - + func testDelete() async throws { await setup(withModels: PostComment8Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) try await deleteAndWaitForSync(savedPost) - + // The expected behavior when deleting a post should be that the // child models are deleted (comment) followed by the parent model (post). try await assertModelDoesNotExist(savedPost) // Is there a way to delete the children models in uni directional relationships? try await assertModelExists(savedComment) } - + func testObservePost() async throws { await setup(withModels: PostComment8Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Post.self) Task { @@ -191,27 +209,29 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: PostComment8Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Comment.self) Task { @@ -225,26 +245,28 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostComment8Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Post.self, where: Post.keys.postId == post.postId) Task { @@ -256,28 +278,30 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: PostComment8Models()) try await startAndWaitForReady() - + let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) - let comment = Comment(commentId: UUID().uuidString, - content: "content", - postId: post.postId, - postTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + postId: post.postId, + postTitle: post.title + ) let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Comment.self, where: Comment.keys.commentId == comment.commentId) Task { @@ -288,14 +312,14 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -304,7 +328,7 @@ final class AWSDataStoreLazyLoadPostComment8Tests: AWSDataStoreLazyLoadBaseTest extension AWSDataStoreLazyLoadPostComment8Tests { typealias Post = Post8 typealias Comment = Comment8 - + struct PostComment8Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8+Schema.swift index 1f74e46906..2f2568baef 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case content case postId @@ -12,21 +19,21 @@ extension Comment8 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment8 = Comment8.keys - + model.pluralName = "Comment8s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .index(fields: ["postId", "postTitle"], name: "byPost"), .primaryKey(fields: [comment8.commentId, comment8.content]) ) - + model.fields( .field(comment8.commentId, is: .required, ofType: .string), .field(comment8.content, is: .required, ofType: .string), @@ -36,10 +43,10 @@ extension Comment8 { .field(comment8.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment8: ModelIdentifiable { @@ -47,10 +54,12 @@ extension Comment8: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment8.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment8.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8.swift index 22fcd26a4b..0fc5456492 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Comment8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Comment8: Model { public var postTitle: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(commentId: String, - content: String, - postId: String? = nil, - postTitle: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + postId: String? = nil, + postTitle: String? = nil + ) { + self.init( + commentId: commentId, content: content, postId: postId, postTitle: postTitle, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(commentId: String, - content: String, - postId: String? = nil, - postTitle: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + commentId: String, + content: String, + postId: String? = nil, + postTitle: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.commentId = commentId self.content = content self.postId = postId @@ -34,4 +47,4 @@ public struct Comment8: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8+Schema.swift index 3778ad3bfa..93f32fa772 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post8 = Post8.keys - + model.pluralName = "Post8s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post8.postId, post8.title]) ) - + model.fields( .field(post8.postId, is: .required, ofType: .string), .field(post8.title, is: .required, ofType: .string), @@ -33,10 +40,10 @@ extension Post8 { .field(post8.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post8: ModelIdentifiable { @@ -44,10 +51,12 @@ extension Post8: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post8.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post8.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8.swift index 440cd2b9d7..eb60ae8287 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL11/Post8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post8: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildSansTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildSansTests.swift index 27c69259d8..68bcee2c5d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildSansTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildSansTests.swift @@ -5,34 +5,35 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadCompositePKTests { - + // MARK: - CompositePKParent / ChildSansBelongsTo - + func initChildSansBelongsTo(with parent: CompositePKParent) -> ChildSansBelongsTo { ChildSansBelongsTo( childId: UUID().uuidString, content: "content", compositePKParentChildrenSansBelongsToCustomId: parent.customId, - compositePKParentChildrenSansBelongsToContent: parent.content) + compositePKParentChildrenSansBelongsToContent: parent.content + ) } - + func testSaveChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChildSansBelongsTo(with: savedParent) try await createAndWaitForSync(child) } - + func testUpdateChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -41,7 +42,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { var savedChild = try await createAndWaitForSync(child) XCTAssertEqual(savedChild.compositePKParentChildrenSansBelongsToCustomId, savedParent.customId) XCTAssertEqual(savedChild.compositePKParentChildrenSansBelongsToContent, savedParent.content) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await createAndWaitForSync(newParent) @@ -51,38 +52,43 @@ extension AWSDataStoreLazyLoadCompositePKTests { XCTAssertEqual(updatedChild.compositePKParentChildrenSansBelongsToCustomId, savedNewParent.customId) XCTAssertEqual(updatedChild.compositePKParentChildrenSansBelongsToContent, savedNewParent.content) } - + func testDeleteChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChildSansBelongsTo(with: parent) let savedChild = try await createAndWaitForSync(child) - + try await deleteAndWaitForSync(savedChild) try await assertModelDoesNotExist(savedChild) - + try await deleteAndWaitForSync(savedParent) try await assertModelDoesNotExist(savedParent) } - + func testGetChildSansBelongsTo() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChildSansBelongsTo(with: parent) let savedChild = try await createAndWaitForSync(child) - + // query parent and load the children let queriedParent = try await query(for: savedParent) - assertList(queriedParent.childrenSansBelongsTo!, state: .isNotLoaded(associatedIds: [queriedParent.customId, - queriedParent.content], - associatedFields: [ - "compositePKParentChildrenSansBelongsToCustomId", - "compositePKParentChildrenSansBelongsToContent"])) + assertList(queriedParent.childrenSansBelongsTo!, state: .isNotLoaded( + associatedIds: [ + queriedParent.customId, + queriedParent.content + ], + associatedFields: [ + "compositePKParentChildrenSansBelongsToCustomId", + "compositePKParentChildrenSansBelongsToContent" + ] + )) try await queriedParent.childrenSansBelongsTo?.fetch() assertList(queriedParent.childrenSansBelongsTo!, state: .isLoaded(count: 1)) - + // query children and verify the parent - ChildSansBelongsTo let queriedChildSansBelongsTo = try await query(for: savedChild) XCTAssertEqual(queriedChildSansBelongsTo.compositePKParentChildrenSansBelongsToCustomId, savedParent.customId) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildTests.swift index 531c18807d..df9deaa7bc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKChildTests.swift @@ -5,30 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadCompositePKTests { - + // MARK: - CompositePKParent / CompositePKChild - + func initChild(with parent: CompositePKParent? = nil) -> CompositePKChild { CompositePKChild(childId: UUID().uuidString, content: "content", parent: parent) } - + func testSaveCompositePKChild() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChild(with: savedParent) try await createAndWaitForSync(child) } - + func testUpdateCompositePKChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -37,7 +37,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { var savedChild = try await createAndWaitForSync(child) let loadedParent = try await savedChild.parent XCTAssertEqual(loadedParent?.identifier, savedParent.identifier) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await createAndWaitForSync(newParent) @@ -46,60 +46,66 @@ extension AWSDataStoreLazyLoadCompositePKTests { let loadedNewParent = try await updatedChild.parent XCTAssertEqual(loadedNewParent?.identifier, savedNewParent.identifier) } - + func testUpdateFromNoParentCompositePKChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) - + let childWithoutParent = initChild() var savedChild = try await createAndWaitForSync(childWithoutParent) let nilParent = try await savedChild.parent XCTAssertNil(nilParent) - + // update the child to a parent savedChild.setParent(savedParent) let savedChildWithParent = try await updateAndWaitForSync(savedChild) let loadedParent = try await savedChildWithParent.parent XCTAssertEqual(loadedParent?.identifier, savedParent.identifier) } - + func testDeleteCompositePKChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChild(with: parent) let savedChild = try await createAndWaitForSync(child) - + try await deleteAndWaitForSync(savedParent) try await assertModelDoesNotExist(savedParent) try await assertModelDoesNotExist(savedChild) } - + func testGetCompositePKChild() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initChild(with: parent) let savedCompositePKChild = try await createAndWaitForSync(child) - + // query parent and load the children let queriedParent = try await query(for: savedParent) - assertList(queriedParent.children!, state: .isNotLoaded(associatedIds: [queriedParent.identifier], - associatedFields: ["parent"])) + assertList(queriedParent.children!, state: .isNotLoaded( + associatedIds: [queriedParent.identifier], + associatedFields: ["parent"] + )) try await queriedParent.children?.fetch() assertList(queriedParent.children!, state: .isLoaded(count: 1)) - + // query child and load the parent - CompositePKChild let queriedCompositePKChild = try await query(for: savedCompositePKChild) - assertLazyReference(queriedCompositePKChild._parent, - state: .notLoaded(identifiers: [ - .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), - .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) - ])) + assertLazyReference( + queriedCompositePKChild._parent, + state: .notLoaded(identifiers: [ + .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), + .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) + ]) + ) let loadedParent = try await queriedCompositePKChild.parent - assertLazyReference(queriedCompositePKChild._parent, - state: .loaded(model: loadedParent)) + assertLazyReference( + queriedCompositePKChild._parent, + state: .loaded(model: loadedParent) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKImplicitTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKImplicitTests.swift index b2ffec5fd6..fa4134f8e6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKImplicitTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKImplicitTests.swift @@ -5,30 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadCompositePKTests { - + // MARK: - CompositePKParent / ImplicitChild - + func initImplicitChild(with parent: CompositePKParent) -> ImplicitChild { ImplicitChild(childId: UUID().uuidString, content: UUID().uuidString, parent: parent) } - + func testSaveImplicitChild() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initImplicitChild(with: savedParent) try await createAndWaitForSync(child) } - + func testUpdateImplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -37,7 +37,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { var savedChild = try await createAndWaitForSync(child) let loadedParent = try await savedChild.parent XCTAssertEqual(loadedParent.identifier, savedParent.identifier) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await createAndWaitForSync(newParent) @@ -45,47 +45,53 @@ extension AWSDataStoreLazyLoadCompositePKTests { let updatedChild = try await updateAndWaitForSync(savedChild) let loadedNewParent = try await updatedChild.parent XCTAssertEqual(loadedNewParent.identifier, savedNewParent.identifier) - + } - + func testDeleteImplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initImplicitChild(with: parent) let savedChild = try await createAndWaitForSync(child) - + try await deleteAndWaitForSync(savedChild) try await assertModelDoesNotExist(savedChild) try await deleteAndWaitForSync(savedParent) try await assertModelDoesNotExist(savedParent) } - + func testGetImplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initImplicitChild(with: parent) let savedChild = try await createAndWaitForSync(child) - + // query parent and load the children let queriedParent = try await query(for: savedParent) - - assertList(queriedParent.implicitChildren!, state: .isNotLoaded(associatedIds: [queriedParent.identifier], - associatedFields: ["parent"])) + + assertList(queriedParent.implicitChildren!, state: .isNotLoaded( + associatedIds: [queriedParent.identifier], + associatedFields: ["parent"] + )) try await queriedParent.implicitChildren?.fetch() assertList(queriedParent.implicitChildren!, state: .isLoaded(count: 1)) - - + + // query child and load the parent - ImplicitChild let queriedImplicitChild = try await query(for: savedChild) - assertLazyReference(queriedImplicitChild._parent, - state: .notLoaded(identifiers: [ - .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), - .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) - ])) + assertLazyReference( + queriedImplicitChild._parent, + state: .notLoaded(identifiers: [ + .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), + .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) + ]) + ) let loadedParent = try await queriedImplicitChild.parent - assertLazyReference(queriedImplicitChild._parent, - state: .loaded(model: loadedParent)) + assertLazyReference( + queriedImplicitChild._parent, + state: .loaded(model: loadedParent) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKSnapshotTests.swift index c135c6520c..334ec2b31e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKSnapshotTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadCompositePKTests { @@ -28,7 +28,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { - All subscription GraphQL requests on `CompositePKParent` model have correct selection set */ func testCompositePKParent_withGraphQLOperations_generateCorrectSelectionSets() { - Operation.allOperations(on: CompositePKParent.schema, model: CompositePKParent.self).forEach { operation in + for operation in Operation.allOperations(on: CompositePKParent.schema, model: CompositePKParent.self) { let expectedDocument = operation.expectedDocument XCTAssertNotNil(expectedDocument) XCTAssertEqual(operation.graphQLRequest?.document, expectedDocument) @@ -44,7 +44,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { - All subscription GraphQL requests on `CompositePKChild` model have correct selection set */ func testCompositePKChild_withGraphQLOperations_generateCorrectSelectionSets() { - Operation.allOperations(on: CompositePKChild.schema, model: CompositePKChild.self).forEach { operation in + for operation in Operation.allOperations(on: CompositePKChild.schema, model: CompositePKChild.self) { let expectedDocument = operation.expectedDocument XCTAssertNotNil(expectedDocument) XCTAssertEqual(operation.graphQLRequest?.document, expectedDocument) @@ -60,7 +60,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { - All subscription GraphQL requests on `ChildSansBelongsTo` model have correct selection set */ func testChildSansBelongsTo_withGraphQLOperations_generateCorrectSelectionSets() { - Operation.allOperations(on: ChildSansBelongsTo.schema, model: ChildSansBelongsTo.self).forEach { operation in + for operation in Operation.allOperations(on: ChildSansBelongsTo.schema, model: ChildSansBelongsTo.self) { let expectedDocument = operation.expectedDocument XCTAssertNotNil(expectedDocument) XCTAssertEqual(operation.graphQLRequest?.document, expectedDocument) @@ -76,7 +76,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { - All subscription GraphQL requests on `ImplicitChild` model have correct selection set */ func testImplicitChild_withGraphQLOperations_generateCorrectSelectionSets() { - Operation.allOperations(on: ImplicitChild.schema, model: ImplicitChild.self).forEach { operation in + for operation in Operation.allOperations(on: ImplicitChild.schema, model: ImplicitChild.self) { let expectedDocument = operation.expectedDocument XCTAssertNotNil(expectedDocument) XCTAssertEqual(operation.graphQLRequest?.document, expectedDocument) @@ -92,7 +92,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { - All subscription GraphQL requests on `StrangeExplicitChild` model have correct selection set */ func testStrangeExplicitChild_withGraphQLOperations_generateCorrectSelectionSets() { - Operation.allOperations(on: StrangeExplicitChild.schema, model: StrangeExplicitChild.self).forEach { operation in + for operation in Operation.allOperations(on: StrangeExplicitChild.schema, model: StrangeExplicitChild.self) { let expectedDocument = operation.expectedDocument XCTAssertNotNil(expectedDocument) XCTAssertEqual(operation.graphQLRequest?.document, expectedDocument) @@ -101,7 +101,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { } -fileprivate enum Operation { +private enum Operation { case mutation(String, ModelSchema, Model.Type) case subscription(GraphQLSubscriptionType, ModelSchema, Model.Type) @@ -171,7 +171,7 @@ fileprivate enum Operation { } } -fileprivate protocol RandomTestSampleInstance { +private protocol RandomTestSampleInstance { static func randomInstance() -> Model static func mutationDocument(operation: String) -> String static func subscriptionDocument(operation: GraphQLSubscriptionType) -> String diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKStrangeExplicitTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKStrangeExplicitTests.swift index 54bf4118c4..e1ab8867d2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKStrangeExplicitTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKStrangeExplicitTests.swift @@ -5,30 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadCompositePKTests { - + // MARK: - CompositePKParent / StrangeExplicitChild - + func initStrangeExplicitChild(with parent: CompositePKParent) -> StrangeExplicitChild { StrangeExplicitChild(strangeId: UUID().uuidString, content: "content", parent: parent) } - + func testSaveStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) - + let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initStrangeExplicitChild(with: savedParent) try await createAndWaitForSync(child) } - + func testUpdateStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -37,7 +37,7 @@ extension AWSDataStoreLazyLoadCompositePKTests { var savedChild = try await createAndWaitForSync(child) let loadedParent = try await savedChild.parent XCTAssertEqual(loadedParent.identifier, savedParent.identifier) - + // update the child to a new parent let newParent = initParent() let savedNewParent = try await createAndWaitForSync(newParent) @@ -45,46 +45,52 @@ extension AWSDataStoreLazyLoadCompositePKTests { let updatedChild = try await updateAndWaitForSync(savedChild) let loadedNewParent = try await updatedChild.parent XCTAssertEqual(loadedNewParent.identifier, savedNewParent.identifier) - + } - + func testDeleteStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initStrangeExplicitChild(with: parent) let savedChild = try await createAndWaitForSync(child) - + try await deleteAndWaitForSync(savedChild) try await assertModelDoesNotExist(savedChild) try await deleteAndWaitForSync(savedParent) try await assertModelDoesNotExist(savedParent) } - + func testGetStrangeExplicitChild() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() let savedParent = try await createAndWaitForSync(parent) let child = initStrangeExplicitChild(with: parent) let savedChild = try await createAndWaitForSync(child) - + // query parent and load the children let queriedParent = try await query(for: savedParent) - - assertList(queriedParent.strangeChildren!, state: .isNotLoaded(associatedIds: [queriedParent.identifier], - associatedFields: ["parent"])) + + assertList(queriedParent.strangeChildren!, state: .isNotLoaded( + associatedIds: [queriedParent.identifier], + associatedFields: ["parent"] + )) try await queriedParent.strangeChildren?.fetch() assertList(queriedParent.strangeChildren!, state: .isLoaded(count: 1)) - + // query children and load the parent - StrangeExplicitChild let queriedStrangeImplicitChild = try await query(for: savedChild) - assertLazyReference(queriedStrangeImplicitChild._parent, - state: .notLoaded(identifiers: [ - .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), - .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) - ])) + assertLazyReference( + queriedStrangeImplicitChild._parent, + state: .notLoaded(identifiers: [ + .init(name: CompositePKParent.keys.customId.stringValue, value: savedParent.customId), + .init(name: CompositePKParent.keys.content.stringValue, value: savedParent.content) + ]) + ) let loadedParent3 = try await queriedStrangeImplicitChild.parent - assertLazyReference(queriedStrangeImplicitChild._parent, - state: .loaded(model: loadedParent3)) + assertLazyReference( + queriedStrangeImplicitChild._parent, + state: .loaded(model: loadedParent3) + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKTests.swift index df13ac6f85..8c1513a5fb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/AWSDataStoreLazyLoadCompositePKTests.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadCompositePKTests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: CompositePKModels()) try await startAndWaitForReady() } - + func testSaveCompositePKParent() async throws { await setup(withModels: CompositePKModels()) let parent = initParent() @@ -27,7 +27,7 @@ class AWSDataStoreLazyLoadCompositePKTests: AWSDataStoreLazyLoadBaseTest { } extension AWSDataStoreLazyLoadCompositePKTests { - + struct CompositePKModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -38,9 +38,11 @@ extension AWSDataStoreLazyLoadCompositePKTests { ModelRegistry.register(modelType: ChildSansBelongsTo.self) } } - + func initParent() -> CompositePKParent { - CompositePKParent(customId: UUID().uuidString, - content: UUID().uuidString) + CompositePKParent( + customId: UUID().uuidString, + content: UUID().uuidString + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift index 1f4e006ad2..e7abeb3b2a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ChildSansBelongsTo { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ChildSansBelongsTo { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case childId case content case compositePKParentChildrenSansBelongsToCustomId @@ -12,21 +19,21 @@ extension ChildSansBelongsTo { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let childSansBelongsTo = ChildSansBelongsTo.keys - + model.pluralName = "ChildSansBelongsTos" - + model.attributes( .index(fields: ["childId", "content"], name: nil), .index(fields: ["compositePKParentChildrenSansBelongsToCustomId", "compositePKParentChildrenSansBelongsToContent"], name: "byParent"), .primaryKey(fields: [childSansBelongsTo.childId, childSansBelongsTo.content]) ) - + model.fields( .field(childSansBelongsTo.childId, is: .required, ofType: .string), .field(childSansBelongsTo.content, is: .required, ofType: .string), @@ -36,9 +43,9 @@ extension ChildSansBelongsTo { .field(childSansBelongsTo.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ChildSansBelongsTo: ModelIdentifiable { @@ -46,29 +53,31 @@ extension ChildSansBelongsTo: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ChildSansBelongsTo.IdentifierProtocol { - public static func identifier(childId: String, - content: String) -> Self { - .make(fields:[(name: "childId", value: childId), (name: "content", value: content)]) +public extension ChildSansBelongsTo.IdentifierProtocol { + static func identifier( + childId: String, + content: String + ) -> Self { + .make(fields: [(name: "childId", value: childId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == ChildSansBelongsTo { - public var childId: FieldPath { - string("childId") +public extension ModelPath where ModelType == ChildSansBelongsTo { + var childId: FieldPath { + string("childId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var compositePKParentChildrenSansBelongsToCustomId: FieldPath { - string("compositePKParentChildrenSansBelongsToCustomId") + var compositePKParentChildrenSansBelongsToCustomId: FieldPath { + string("compositePKParentChildrenSansBelongsToCustomId") } - public var compositePKParentChildrenSansBelongsToContent: FieldPath { - string("compositePKParentChildrenSansBelongsToContent") + var compositePKParentChildrenSansBelongsToContent: FieldPath { + string("compositePKParentChildrenSansBelongsToContent") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift index 47af9e3213..6ebf5f53be 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ChildSansBelongsTo.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct ChildSansBelongsTo: Model { public var compositePKParentChildrenSansBelongsToContent: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(childId: String, + + public init( + childId: String, content: String, compositePKParentChildrenSansBelongsToCustomId: String, - compositePKParentChildrenSansBelongsToContent: String? = nil) { - self.init(childId: childId, - content: content, - compositePKParentChildrenSansBelongsToCustomId: compositePKParentChildrenSansBelongsToCustomId, - compositePKParentChildrenSansBelongsToContent: compositePKParentChildrenSansBelongsToContent, - createdAt: nil, - updatedAt: nil) + compositePKParentChildrenSansBelongsToContent: String? = nil + ) { + self.init( + childId: childId, + content: content, + compositePKParentChildrenSansBelongsToCustomId: compositePKParentChildrenSansBelongsToCustomId, + compositePKParentChildrenSansBelongsToContent: compositePKParentChildrenSansBelongsToContent, + createdAt: nil, + updatedAt: nil + ) } - internal init(childId: String, + init( + childId: String, content: String, compositePKParentChildrenSansBelongsToCustomId: String, compositePKParentChildrenSansBelongsToContent: String? = nil, createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + updatedAt: Temporal.DateTime? = nil + ) { self.childId = childId self.content = content self.compositePKParentChildrenSansBelongsToCustomId = compositePKParentChildrenSansBelongsToCustomId @@ -36,12 +49,12 @@ public struct ChildSansBelongsTo: Model { } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - childId = try values.decode(String.self, forKey: .childId) - content = try values.decode(String.self, forKey: .content) - compositePKParentChildrenSansBelongsToCustomId = try values.decode(String.self, forKey: .compositePKParentChildrenSansBelongsToCustomId) - compositePKParentChildrenSansBelongsToContent = try values.decode(String?.self, forKey: .compositePKParentChildrenSansBelongsToContent) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.childId = try values.decode(String.self, forKey: .childId) + self.content = try values.decode(String.self, forKey: .content) + self.compositePKParentChildrenSansBelongsToCustomId = try values.decode(String.self, forKey: .compositePKParentChildrenSansBelongsToCustomId) + self.compositePKParentChildrenSansBelongsToContent = try values.decode(String?.self, forKey: .compositePKParentChildrenSansBelongsToContent) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -52,4 +65,4 @@ public struct ChildSansBelongsTo: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift index 6360f82b98..fb7c116016 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CompositePKChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension CompositePKChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case childId case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let compositePKChild = CompositePKChild.keys - + model.pluralName = "CompositePKChildren" - + model.attributes( .index(fields: ["childId", "content"], name: nil), .index(fields: ["parentId", "parentTitle"], name: "byParent"), .primaryKey(fields: [compositePKChild.childId, compositePKChild.content]) ) - + model.fields( .field(compositePKChild.childId, is: .required, ofType: .string), .field(compositePKChild.content, is: .required, ofType: .string), @@ -34,9 +41,9 @@ extension CompositePKChild { .field(compositePKChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension CompositePKChild: ModelIdentifiable { @@ -44,26 +51,28 @@ extension CompositePKChild: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CompositePKChild.IdentifierProtocol { - public static func identifier(childId: String, - content: String) -> Self { - .make(fields:[(name: "childId", value: childId), (name: "content", value: content)]) +public extension CompositePKChild.IdentifierProtocol { + static func identifier( + childId: String, + content: String + ) -> Self { + .make(fields: [(name: "childId", value: childId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == CompositePKChild { - public var childId: FieldPath { - string("childId") +public extension ModelPath where ModelType == CompositePKChild { + var childId: FieldPath { + string("childId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - CompositePKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + CompositePKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift index 3ade723583..773d3e412c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct CompositePKChild: Model { public let childId: String public let content: String - internal var _parent: LazyReference + var _parent: LazyReference public var parent: CompositePKParent? { - get async throws { + get async throws { try await _parent.get() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(childId: String, - content: String, - parent: CompositePKParent? = nil) { - self.init(childId: childId, + + public init( + childId: String, + content: String, + parent: CompositePKParent? = nil + ) { + self.init( + childId: childId, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(childId: String, - content: String, - parent: CompositePKParent? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + childId: String, + content: String, + parent: CompositePKParent? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.childId = childId self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct CompositePKChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: CompositePKParent? = nil) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - childId = try values.decode(String.self, forKey: .childId) - content = try values.decode(String.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.childId = try values.decode(String.self, forKey: .childId) + self.content = try values.decode(String.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift index e047f0dc3e..0b8341d9c1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CompositePKParent { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension CompositePKParent { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case customId case content case children @@ -14,20 +21,20 @@ extension CompositePKParent { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let compositePKParent = CompositePKParent.keys - + model.pluralName = "CompositePKParents" - + model.attributes( .index(fields: ["customId", "content"], name: nil), .primaryKey(fields: [compositePKParent.customId, compositePKParent.content]) ) - + model.fields( .field(compositePKParent.customId, is: .required, ofType: .string), .field(compositePKParent.content, is: .required, ofType: .string), @@ -39,9 +46,9 @@ extension CompositePKParent { .field(compositePKParent.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension CompositePKParent: ModelIdentifiable { @@ -49,35 +56,37 @@ extension CompositePKParent: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CompositePKParent.IdentifierProtocol { - public static func identifier(customId: String, - content: String) -> Self { - .make(fields:[(name: "customId", value: customId), (name: "content", value: content)]) +public extension CompositePKParent.IdentifierProtocol { + static func identifier( + customId: String, + content: String + ) -> Self { + .make(fields: [(name: "customId", value: customId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == CompositePKParent { - public var customId: FieldPath { - string("customId") +public extension ModelPath where ModelType == CompositePKParent { + var customId: FieldPath { + string("customId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var children: ModelPath { - CompositePKChild.Path(name: "children", isCollection: true, parent: self) + var children: ModelPath { + CompositePKChild.Path(name: "children", isCollection: true, parent: self) } - public var implicitChildren: ModelPath { - ImplicitChild.Path(name: "implicitChildren", isCollection: true, parent: self) + var implicitChildren: ModelPath { + ImplicitChild.Path(name: "implicitChildren", isCollection: true, parent: self) } - public var strangeChildren: ModelPath { - StrangeExplicitChild.Path(name: "strangeChildren", isCollection: true, parent: self) + var strangeChildren: ModelPath { + StrangeExplicitChild.Path(name: "strangeChildren", isCollection: true, parent: self) } - public var childrenSansBelongsTo: ModelPath { - ChildSansBelongsTo.Path(name: "childrenSansBelongsTo", isCollection: true, parent: self) + var childrenSansBelongsTo: ModelPath { + ChildSansBelongsTo.Path(name: "childrenSansBelongsTo", isCollection: true, parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift index d2bef97b61..12a4f511fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/CompositePKParent.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -11,30 +18,36 @@ public struct CompositePKParent: Model { public var childrenSansBelongsTo: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(customId: String, - content: String, - children: List? = [], - implicitChildren: List? = [], - strangeChildren: List? = [], - childrenSansBelongsTo: List? = []) { - self.init(customId: customId, + + public init( + customId: String, + content: String, + children: List? = [], + implicitChildren: List? = [], + strangeChildren: List? = [], + childrenSansBelongsTo: List? = [] + ) { + self.init( + customId: customId, content: content, children: children, implicitChildren: implicitChildren, strangeChildren: strangeChildren, childrenSansBelongsTo: childrenSansBelongsTo, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(customId: String, - content: String, - children: List? = [], - implicitChildren: List? = [], - strangeChildren: List? = [], - childrenSansBelongsTo: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + customId: String, + content: String, + children: List? = [], + implicitChildren: List? = [], + strangeChildren: List? = [], + childrenSansBelongsTo: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.customId = customId self.content = content self.children = children diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift index 83d53e59e2..cbbbd263a8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ImplicitChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ImplicitChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case childId case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let implicitChild = ImplicitChild.keys - + model.pluralName = "ImplicitChildren" - + model.attributes( .index(fields: ["childId", "content"], name: nil), .primaryKey(fields: [implicitChild.childId, implicitChild.content]) ) - + model.fields( .field(implicitChild.childId, is: .required, ofType: .string), .field(implicitChild.content, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension ImplicitChild { .field(implicitChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ImplicitChild: ModelIdentifiable { @@ -43,26 +50,28 @@ extension ImplicitChild: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension ImplicitChild.IdentifierProtocol { - public static func identifier(childId: String, - content: String) -> Self { - .make(fields:[(name: "childId", value: childId), (name: "content", value: content)]) +public extension ImplicitChild.IdentifierProtocol { + static func identifier( + childId: String, + content: String + ) -> Self { + .make(fields: [(name: "childId", value: childId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == ImplicitChild { - public var childId: FieldPath { - string("childId") +public extension ModelPath where ModelType == ImplicitChild { + var childId: FieldPath { + string("childId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - CompositePKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + CompositePKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift index 78ec7c0f2d..b8f2e21ccb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/ImplicitChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct ImplicitChild: Model { public let childId: String public let content: String - internal var _parent: LazyReference + var _parent: LazyReference public var parent: CompositePKParent { get async throws { try await _parent.require() @@ -13,21 +20,27 @@ public struct ImplicitChild: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(childId: String, - content: String, - parent: CompositePKParent) { - self.init(childId: childId, + + public init( + childId: String, + content: String, + parent: CompositePKParent + ) { + self.init( + childId: childId, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(childId: String, - content: String, - parent: CompositePKParent, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + childId: String, + content: String, + parent: CompositePKParent, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.childId = childId self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct ImplicitChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: CompositePKParent) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - childId = try values.decode(String.self, forKey: .childId) - content = try values.decode(String.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.childId = try values.decode(String.self, forKey: .childId) + self.content = try values.decode(String.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift index 33af033c9b..172e7a9b4c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension StrangeExplicitChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension StrangeExplicitChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case strangeId case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let strangeExplicitChild = StrangeExplicitChild.keys - + model.pluralName = "StrangeExplicitChildren" - + model.attributes( .index(fields: ["strangeId", "content"], name: nil), .index(fields: ["strangeParentId", "strangeParentTitle"], name: "byCompositePKParentX"), .primaryKey(fields: [strangeExplicitChild.strangeId, strangeExplicitChild.content]) ) - + model.fields( .field(strangeExplicitChild.strangeId, is: .required, ofType: .string), .field(strangeExplicitChild.content, is: .required, ofType: .string), @@ -34,9 +41,9 @@ extension StrangeExplicitChild { .field(strangeExplicitChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension StrangeExplicitChild: ModelIdentifiable { @@ -44,26 +51,28 @@ extension StrangeExplicitChild: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension StrangeExplicitChild.IdentifierProtocol { - public static func identifier(strangeId: String, - content: String) -> Self { - .make(fields:[(name: "strangeId", value: strangeId), (name: "content", value: content)]) +public extension StrangeExplicitChild.IdentifierProtocol { + static func identifier( + strangeId: String, + content: String + ) -> Self { + .make(fields: [(name: "strangeId", value: strangeId), (name: "content", value: content)]) } } -extension ModelPath where ModelType == StrangeExplicitChild { - public var strangeId: FieldPath { - string("strangeId") +public extension ModelPath where ModelType == StrangeExplicitChild { + var strangeId: FieldPath { + string("strangeId") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - CompositePKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + CompositePKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift index c0fd404bb9..0e004fc8f3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/CompositePK/StrangeExplicitChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct StrangeExplicitChild: Model { public let strangeId: String public let content: String - internal var _parent: LazyReference + var _parent: LazyReference public var parent: CompositePKParent { - get async throws { + get async throws { try await _parent.require() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(strangeId: String, - content: String, - parent: CompositePKParent) { - self.init(strangeId: strangeId, + + public init( + strangeId: String, + content: String, + parent: CompositePKParent + ) { + self.init( + strangeId: strangeId, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(strangeId: String, - content: String, - parent: CompositePKParent, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + strangeId: String, + content: String, + parent: CompositePKParent, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.strangeId = strangeId self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct StrangeExplicitChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: CompositePKParent) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - strangeId = try values.decode(String.self, forKey: .strangeId) - content = try values.decode(String.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.strangeId = try values.decode(String.self, forKey: .strangeId) + self.content = try values.decode(String.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKSnapshotTests.swift index 71bbfd2c58..b7fdf44476 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKSnapshotTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadDefaultPKTests { - + func testParentSelectionSets() { setUpModelRegistrationOnly(withModels: DefaultPKModels()) continueAfterFailure = true @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: parent, modelSchema: Parent.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: parent, modelSchema: Parent.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Parent.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Parent.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Parent.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Parent.self) let syncDocument = """ @@ -148,13 +148,13 @@ extension AWSDataStoreLazyLoadDefaultPKTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testChildSelectionSets() { setUpModelRegistrationOnly(withModels: DefaultPKModels()) continueAfterFailure = true let parent = Parent() let child = Child(parent: parent) - + // Create let createRequest = GraphQLRequest.createMutation(of: child, modelSchema: Child.schema) let createDocument = """ @@ -182,7 +182,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: child, modelSchema: Child.schema) let updateDocument = """ @@ -210,7 +210,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: child, modelSchema: Child.schema) let deleteDocument = """ @@ -238,7 +238,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Child.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -261,7 +261,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Child.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -284,7 +284,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Child.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -307,7 +307,7 @@ extension AWSDataStoreLazyLoadDefaultPKTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Child.self) let syncDocument = """ @@ -335,6 +335,6 @@ extension AWSDataStoreLazyLoadDefaultPKTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKTests.swift index c769340da9..3b98a5bf73 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/AWSDataStoreLazyLoadDefaultPKTests.swift @@ -5,26 +5,26 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: DefaultPKModels()) try await startAndWaitForReady() } - + func testSaveParent() async throws { await setup(withModels: DefaultPKModels()) let parent = Parent() try await createAndWaitForSync(parent) } - + func testSaveChild() async throws { await setup(withModels: DefaultPKModels()) let parent = Parent() @@ -32,10 +32,10 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { try await createAndWaitForSync(parent) try await createAndWaitForSync(child) } - + func testLazyLoad() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) let savedParent = try await createAndWaitForSync(parent) @@ -47,113 +47,135 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { let queriedPost = try await query(for: savedParent) try await assertParent(queriedPost, canLazyLoad: savedChild) } - + func testLazyLoadOnSaveAfterEncodeDecode() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) let savedParent = try await createAndWaitForSync(parent) let savedChild = try await createAndWaitForSync(child) - + guard let encodedChild = try? savedChild.toJSON() else { XCTFail("Could not encode child") return } try await assertChild(savedChild, canLazyLoad: savedParent) - - guard let decodedChild = try? ModelRegistry.decode(modelName: Child.modelName, - from: encodedChild) as? Child else { - + + guard let decodedChild = try? ModelRegistry.decode( + modelName: Child.modelName, + from: encodedChild + ) as? Child else { + XCTFail("Could not decode comment") return } - + try await assertChild(decodedChild, canLazyLoad: savedParent) } - + func testLazyLoadOnQueryAfterEncodeDecoder() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) let savedParent = try await createAndWaitForSync(parent) let savedChild = try await createAndWaitForSync(child) let queriedChild = try await query(for: savedChild) - + guard let encodedChild = try? queriedChild.toJSON() else { XCTFail("Could not encode child") return } - + try await assertChild(queriedChild, canLazyLoad: savedParent) - - guard let decodedChild = try? ModelRegistry.decode(modelName: Child.modelName, - from: encodedChild) as? Child else { - + + guard let decodedChild = try? ModelRegistry.decode( + modelName: Child.modelName, + from: encodedChild + ) as? Child else { + XCTFail("Could not decode comment") return } - + try await assertChild(decodedChild, canLazyLoad: savedParent) } - - func assertChild(_ child: Child, - hasEagerLoaded parent: Parent) async throws { - assertLazyReference(child._parent, - state: .loaded(model: parent)) - + + func assertChild( + _ child: Child, + hasEagerLoaded parent: Parent + ) async throws { + assertLazyReference( + child._parent, + state: .loaded(model: parent) + ) + guard let loadedParent = try await child.parent else { XCTFail("Failed to retrieve the parent from the child") return } XCTAssertEqual(loadedParent.id, parent.id) - + try await assertParent(loadedParent, canLazyLoad: child) } - - func assertChild(_ child: Child, - canLazyLoad parent: Parent) async throws { - assertLazyReference(child._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)])) + + func assertChild( + _ child: Child, + canLazyLoad parent: Parent + ) async throws { + assertLazyReference( + child._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)]) + ) guard let loadedParent = try await child.parent else { XCTFail("Failed to load the parent from the child") return } XCTAssertEqual(loadedParent.id, parent.id) - assertLazyReference(child._parent, - state: .loaded(model: parent)) + assertLazyReference( + child._parent, + state: .loaded(model: parent) + ) try await assertParent(loadedParent, canLazyLoad: child) } - - func assertParent(_ parent: Parent, - canLazyLoad child: Child) async throws { + + func assertParent( + _ parent: Parent, + canLazyLoad child: Child + ) async throws { guard let children = parent.children else { XCTFail("Missing children on parent") return } - assertList(children, state: .isNotLoaded(associatedIds: [parent.identifier], - associatedFields: ["parent"])) - + assertList(children, state: .isNotLoaded( + associatedIds: [parent.identifier], + associatedFields: ["parent"] + )) + try await children.fetch() assertList(children, state: .isLoaded(count: 1)) guard let child = children.first else { XCTFail("Missing lazy loaded child from parent") return } - + // further nested models should not be loaded - assertLazyReference(child._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)])) + assertLazyReference( + child._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)]) + ) } - + func testSaveWithoutPost() async throws { await setup(withModels: DefaultPKModels()) let child = Child(content: "content") let savedChild = try await createAndWaitForSync(child) var queriedChild = try await query(for: savedChild) - assertLazyReference(queriedChild._parent, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedChild._parent, + state: .notLoaded(identifiers: nil) + ) let parent = Parent() let savedParent = try await createAndWaitForSync(parent) queriedChild.setParent(savedParent) @@ -161,7 +183,7 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { let queriedChild2 = try await query(for: saveCommentWithPost) try await assertChild(queriedChild2, canLazyLoad: parent) } - + func testUpdateFromqueriedChild() async throws { await setup(withModels: DefaultPKModels()) let parent = Parent() @@ -169,24 +191,28 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { let savedParent = try await createAndWaitForSync(parent) let savedChild = try await createAndWaitForSync(child) let queriedChild = try await query(for: savedChild) - assertLazyReference(queriedChild._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)])) + assertLazyReference( + queriedChild._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)]) + ) let savedqueriedChild = try await updateAndWaitForSync(queriedChild) let queriedChild2 = try await query(for: savedqueriedChild) try await assertChild(queriedChild2, canLazyLoad: savedParent) } - + func testUpdateToNewPost() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) _ = try await createAndWaitForSync(parent) let savedChild = try await createAndWaitForSync(child) var queriedChild = try await query(for: savedChild) - assertLazyReference(queriedChild._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)])) - + assertLazyReference( + queriedChild._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)]) + ) + let newParent = DefaultPKParent() _ = try await createAndWaitForSync(newParent) queriedChild.setParent(newParent) @@ -194,28 +220,32 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { let queriedChild2 = try await query(for: saveCommentWithNewPost) try await assertChild(queriedChild2, canLazyLoad: newParent) } - + func testUpdateRemovePost() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) _ = try await createAndWaitForSync(parent) let savedChild = try await createAndWaitForSync(child) var queriedChild = try await query(for: savedChild) - assertLazyReference(queriedChild._parent, - state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)])) - + assertLazyReference( + queriedChild._parent, + state: .notLoaded(identifiers: [.init(name: "id", value: parent.identifier)]) + ) + queriedChild.setParent(nil) let saveCommentRemovePost = try await updateAndWaitForSync(queriedChild) let queriedChildNoParent = try await query(for: saveCommentRemovePost) - assertLazyReference(queriedChildNoParent._parent, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedChildNoParent._parent, + state: .notLoaded(identifiers: nil) + ) } - + func testDelete() async throws { await setup(withModels: DefaultPKModels()) - + let parent = Parent() let child = Child(parent: parent) let savedParent = try await createAndWaitForSync(parent) @@ -224,7 +254,7 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { try await assertModelDoesNotExist(savedChild) try await assertModelDoesNotExist(savedParent) } - + func testObserveParent() async throws { await setup(withModels: DefaultPKModels()) try await startAndWaitForReady() @@ -238,9 +268,9 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedParent = try? mutationEvent.decodeModel(as: Parent.self), receivedParent.id == parent.id { - + try await createAndWaitForSync(child) - + guard let children = receivedParent.children else { XCTFail("Lazy List does not exist") return @@ -251,23 +281,23 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load children \(error)") } XCTAssertEqual(children.count, 1) - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: parent, modelSchema: Parent.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveChild() async throws { await setup(withModels: DefaultPKModels()) try await startAndWaitForReady() @@ -287,18 +317,18 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: child, modelSchema: Child.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryParent() async throws { await setup(withModels: DefaultPKModels()) try await startAndWaitForReady() @@ -320,27 +350,27 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load children \(error)") } XCTAssertEqual(children.count, 1) - + snapshotReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: parent, modelSchema: Parent.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryChild() async throws { await setup(withModels: DefaultPKModels()) try await startAndWaitForReady() - + let parent = Parent() let savedParent = try await createAndWaitForSync(parent) let child = Child(parent: parent) @@ -354,24 +384,24 @@ class AWSDataStoreLazyLoadDefaultPKTests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: child, modelSchema: Child.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } } extension AWSDataStoreLazyLoadDefaultPKTests { - + typealias Parent = DefaultPKParent typealias Child = DefaultPKChild - + struct DefaultPKModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift index b2bef9f056..44da59840b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension DefaultPKChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension DefaultPKChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case parent case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let defaultPKChild = DefaultPKChild.keys - + model.pluralName = "DefaultPKChildren" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [defaultPKChild.id]) ) - + model.fields( .field(defaultPKChild.id, is: .required, ofType: .string), .field(defaultPKChild.content, is: .optional, ofType: .string), @@ -33,29 +40,29 @@ extension DefaultPKChild { .field(defaultPKChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension DefaultPKChild: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == DefaultPKChild { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == DefaultPKChild { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var parent: ModelPath { - DefaultPKParent.Path(name: "parent", parent: self) + var parent: ModelPath { + DefaultPKParent.Path(name: "parent", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift index dabbd4888e..e1ef75fd6d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct DefaultPKChild: Model { public let id: String public var content: String? - internal var _parent: LazyReference + var _parent: LazyReference public var parent: DefaultPKParent? { get async throws { try await _parent.get() @@ -13,21 +20,27 @@ public struct DefaultPKChild: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - parent: DefaultPKParent? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + parent: DefaultPKParent? = nil + ) { + self.init( + id: id, content: content, parent: parent, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - parent: DefaultPKParent? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + parent: DefaultPKParent? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._parent = LazyReference(parent) @@ -35,15 +48,15 @@ public struct DefaultPKChild: Model { self.updatedAt = updatedAt } public mutating func setParent(_ parent: DefaultPKParent? = nil) { - self._parent = LazyReference(parent) + _parent = LazyReference(parent) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try? values.decode(String?.self, forKey: .content) - _parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try? values.decode(String?.self, forKey: .content) + self._parent = try values.decodeIfPresent(LazyReference.self, forKey: .parent) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift index d493d3a95f..39c2889c26 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension DefaultPKParent { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension DefaultPKParent { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case children case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let defaultPKParent = DefaultPKParent.keys - + model.pluralName = "DefaultPKParents" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [defaultPKParent.id]) ) - + model.fields( .field(defaultPKParent.id, is: .required, ofType: .string), .field(defaultPKParent.content, is: .optional, ofType: .string), @@ -33,29 +40,29 @@ extension DefaultPKParent { .field(defaultPKParent.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension DefaultPKParent: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == DefaultPKParent { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == DefaultPKParent { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var children: ModelPath { - DefaultPKChild.Path(name: "children", isCollection: true, parent: self) + var children: ModelPath { + DefaultPKChild.Path(name: "children", isCollection: true, parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift index 830d085e35..d2bedd8d1e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/DefaultPK/DefaultPKParent.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,21 +15,27 @@ public struct DefaultPKParent: Model { public var children: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - children: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + children: List? = [] + ) { + self.init( + id: id, content: content, children: children, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - children: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + children: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.children = children diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneSnapshotTests.swift index 5688cdd524..423ca27fde 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneSnapshotTests.swift @@ -5,21 +5,21 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadHasOneTests { - + func testHasOneParentSelectionSets() { setUpModelRegistrationOnly(withModels: HasOneModels()) continueAfterFailure = true let child = HasOneChild() let parent = HasOneParent(child: child, hasOneParentChildId: child.id) - + // Create let createRequest = GraphQLRequest.createMutation(of: parent, modelSchema: HasOneParent.schema) let createDocument = """ @@ -47,7 +47,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: parent, modelSchema: HasOneParent.schema) let updateDocument = """ @@ -75,7 +75,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: parent, modelSchema: HasOneParent.schema) let deleteDocument = """ @@ -103,7 +103,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: HasOneParent.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -126,7 +126,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: HasOneParent.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -149,7 +149,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: HasOneParent.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -172,7 +172,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: HasOneParent.self) let syncDocument = """ @@ -200,12 +200,12 @@ extension AWSDataStoreLazyLoadHasOneTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testHasOneChildSelectionSets() { setUpModelRegistrationOnly(withModels: HasOneModels()) continueAfterFailure = true let child = HasOneChild() - + // Create let createRequest = GraphQLRequest.createMutation(of: child, modelSchema: HasOneChild.schema) let createDocument = """ @@ -223,7 +223,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: child, modelSchema: HasOneChild.schema) let updateDocument = """ @@ -241,7 +241,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: child, modelSchema: HasOneChild.schema) let deleteDocument = """ @@ -259,7 +259,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: HasOneChild.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -277,7 +277,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: HasOneChild.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -295,7 +295,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: HasOneChild.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -313,7 +313,7 @@ extension AWSDataStoreLazyLoadHasOneTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: HasOneChild.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneTests.swift index 72b44fb797..7645269868 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/AWSDataStoreLazyLoadHasOneTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { @@ -64,12 +64,12 @@ class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { // populating `hasOneParentChildId` is required to sync successfully let parent = HasOneParent(child: child, hasOneParentChildId: child.id) try await createAndWaitForSync(parent) - + // Query from API let response = try await Amplify.API.query(request: .get(HasOneParent.self, byId: parent.id)) switch response { case .success(let queriedParent): - guard let queriedParent = queriedParent else { + guard let queriedParent else { XCTFail("Unexpected, query should return model") return } @@ -81,19 +81,19 @@ class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { case .failure(let error): XCTFail("Error querying for parent directly from AppSync \(error)") } - + // Query from DataStore let queriedParent = try await query(for: parent) - + // The child can be lazy loaded. assertLazyReference(queriedParent._child, state: .notLoaded(identifiers: [.init(name: "id", value: child.id)])) let queriedParentChild = try await queriedParent.child! XCTAssertEqual(queriedParentChild.id, child.id) - + // The child model id can be found on the explicit field. let childId = queriedParent.hasOneParentChildId XCTAssertEqual(childId, child.id) - + // Delete try await deleteAndWaitForSync(parent) try await assertModelDoesNotExist(parent) @@ -121,10 +121,12 @@ class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { XCTAssertEqual(queriedParent.hasOneParentChildId, savedChild.id) // The child can be lazy loaded. - assertLazyReference(queriedParent._child, - state: .notLoaded(identifiers: [ - .init(name: HasOneChild.keys.id.stringValue, value: child.id) - ])) + assertLazyReference( + queriedParent._child, + state: .notLoaded(identifiers: [ + .init(name: HasOneChild.keys.id.stringValue, value: child.id) + ]) + ) let newChild = HasOneChild() let savedNewChild = try await createAndWaitForSync(newChild) @@ -162,8 +164,7 @@ class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { if let version = mutationEvent.version, version == 1, let receivedChild = try? mutationEvent.decodeModel(as: HasOneChild.self), - receivedChild.identifier == child.identifier - { + receivedChild.identifier == child.identifier { mutationEventReceived.fulfill() } } @@ -268,7 +269,7 @@ class AWSDataStoreLazyLoadHasOneTests: AWSDataStoreLazyLoadBaseTest { } extension AWSDataStoreLazyLoadHasOneTests { - + struct HasOneModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift index 5256e3b18a..9a67ca4452 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension HasOneChild { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension HasOneChild { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let hasOneChild = HasOneChild.keys - + model.pluralName = "HasOneChildren" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [hasOneChild.id]) ) - + model.fields( .field(hasOneChild.id, is: .required, ofType: .string), .field(hasOneChild.content, is: .optional, ofType: .string), @@ -31,26 +38,26 @@ extension HasOneChild { .field(hasOneChild.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension HasOneChild: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == HasOneChild { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == HasOneChild { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift index 20714ad8e0..1e37821e08 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneChild.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,18 +14,24 @@ public struct HasOneChild: Model { public var content: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift index 6a922e8bd4..f4b24e8e1e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension HasOneParent { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension HasOneParent { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case child case createdAt case updatedAt case hasOneParentChildId } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let hasOneParent = HasOneParent.keys - + model.pluralName = "HasOneParents" - + model.attributes( .index(fields: ["id"], name: nil), .primaryKey(fields: [hasOneParent.id]) ) - + model.fields( .field(hasOneParent.id, is: .required, ofType: .string), .hasOne(hasOneParent.child, is: .optional, ofType: HasOneChild.self, associatedWith: HasOneChild.keys.id, targetNames: ["hasOneParentChildId"]), @@ -33,29 +40,29 @@ extension HasOneParent { .field(hasOneParent.hasOneParentChildId, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension HasOneParent: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == HasOneParent { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == HasOneParent { + var id: FieldPath { + string("id") } - public var child: ModelPath { - HasOneChild.Path(name: "child", parent: self) + var child: ModelPath { + HasOneChild.Path(name: "child", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } - public var hasOneParentChildId: FieldPath { - string("hasOneParentChildId") + var hasOneParentChildId: FieldPath { + string("hasOneParentChildId") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift index 887aedc67d..81931f3e97 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL12/HasOneParentChild/HasOneParent.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation public struct HasOneParent: Model { public let id: String - internal var _child: LazyReference + var _child: LazyReference public var child: HasOneChild? { get async throws { try await _child.get() @@ -13,21 +20,27 @@ public struct HasOneParent: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? public var hasOneParentChildId: String? - - public init(id: String = UUID().uuidString, - child: HasOneChild? = nil, - hasOneParentChildId: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + child: HasOneChild? = nil, + hasOneParentChildId: String? = nil + ) { + self.init( + id: id, child: child, createdAt: nil, updatedAt: nil, - hasOneParentChildId: hasOneParentChildId) + hasOneParentChildId: hasOneParentChildId + ) } - internal init(id: String = UUID().uuidString, - child: HasOneChild? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - hasOneParentChildId: String? = nil) { + init( + id: String = UUID().uuidString, + child: HasOneChild? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + hasOneParentChildId: String? = nil + ) { self.id = id self._child = LazyReference(child) self.createdAt = createdAt @@ -35,15 +48,15 @@ public struct HasOneParent: Model { self.hasOneParentChildId = hasOneParentChildId } public mutating func setChild(_ child: HasOneChild? = nil) { - self._child = LazyReference(child) + _child = LazyReference(child) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - _child = try values.decodeIfPresent(LazyReference.self, forKey: .child) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - hasOneParentChildId = try? values.decode(String?.self, forKey: .hasOneParentChildId) + self.id = try values.decode(String.self, forKey: .id) + self._child = try values.decodeIfPresent(LazyReference.self, forKey: .child) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.hasOneParentChildId = try? values.decode(String?.self, forKey: .hasOneParentChildId) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallSnapshotTests.swift index 28b30a9446..8b801a137a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallSnapshotTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPhoneCallTests { - + } - + diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallTests.swift index 276f3c2632..1ae727ce4f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/AWSDataStoreLazyLoadPhoneCallTests.swift @@ -5,21 +5,21 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: PhoneCallModels()) try await startAndWaitForReady() printDBPath() } - + /// Saving a person should be successfully /// /// - Given: A model instance of a Person @@ -32,7 +32,7 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { let person = Person(name: "name") try await createAndWaitForSync(person) } - + /// Saving a PhoneCall, requires a caller and a callee, should be successful. /// /// - Given: Two saved persons @@ -52,24 +52,28 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { let phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let savedPhoneCall = try await createAndWaitForSync(phoneCall) let queriedPhoneCall = try await query(for: savedPhoneCall) - assertLazyReference(queriedPhoneCall._caller, - state: .notLoaded(identifiers: [.init(name: "id", value: caller.id)])) - assertLazyReference(queriedPhoneCall._callee, - state: .notLoaded(identifiers: [.init(name: "id", value: callee.id)])) + assertLazyReference( + queriedPhoneCall._caller, + state: .notLoaded(identifiers: [.init(name: "id", value: caller.id)]) + ) + assertLazyReference( + queriedPhoneCall._callee, + state: .notLoaded(identifiers: [.init(name: "id", value: callee.id)]) + ) let loadedCaller = try await queriedPhoneCall.caller let loadedCallee = try await queriedPhoneCall.callee assertLazyReference(queriedPhoneCall._caller, state: .loaded(model: savedCaller)) assertLazyReference(queriedPhoneCall._callee, state: .loaded(model: savedCallee)) - + let queriedCaller = try await query(for: caller) try await queriedCaller.callerOf?.fetch() XCTAssertEqual(queriedCaller.callerOf!.count, 1) - + let queriedCallee = try await query(for: callee) try await queriedCallee.calleeOf?.fetch() XCTAssertEqual(queriedCallee.calleeOf!.count, 1) } - + /// Saving a Transcript with a PhoneCall and a PhoneCall with a Transcript, should be successful /// /// - Given: A Transcript with a PhoneCall. A PhoneCall with a Transcript @@ -89,44 +93,50 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { let savedCallee = try await createAndWaitForSync(callee) var phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let transcript = Transcript(text: "text", phoneCall: phoneCall) - + // When the explicit FK and the connected model exists on the model, setting the connected model // has no effect, we have to set the explicit field `phoneCallTranscriptId`. // phoneCall.setTranscript(transcript) phoneCall.phoneCallTranscriptId = transcript.id - + let savedPhoneCall = try await createAndWaitForSync(phoneCall) XCTAssertEqual(savedPhoneCall.phoneCallTranscriptId, transcript.id) let savedTranscript = try await createAndWaitForSync(transcript) - assertLazyReference(savedTranscript._phoneCall, - state: .notLoaded(identifiers: [ - .init(name: PhoneCall.keys.id.stringValue, value: savedPhoneCall.id) - ])) - + assertLazyReference( + savedTranscript._phoneCall, + state: .notLoaded(identifiers: [ + .init(name: PhoneCall.keys.id.stringValue, value: savedPhoneCall.id) + ]) + ) + let queriedTranscript = try await query(for: savedTranscript) - assertLazyReference(queriedTranscript._phoneCall, - state: .notLoaded(identifiers: [ - .init(name: PhoneCall.keys.id.stringValue, value: savedPhoneCall.id) - ])) + assertLazyReference( + queriedTranscript._phoneCall, + state: .notLoaded(identifiers: [ + .init(name: PhoneCall.keys.id.stringValue, value: savedPhoneCall.id) + ]) + ) let loadedPhoneCall = try await queriedTranscript.phoneCall! - assertLazyReference(queriedTranscript._phoneCall, - state: .loaded(model: savedPhoneCall)) + assertLazyReference( + queriedTranscript._phoneCall, + state: .loaded(model: savedPhoneCall) + ) let loadedCaller = try await loadedPhoneCall.caller let loadedCallee = try await loadedPhoneCall.callee - + try await loadedCaller.callerOf?.fetch() XCTAssertEqual(loadedCaller.callerOf!.count, 1) - + try await loadedCaller.calleeOf?.fetch() XCTAssertEqual(loadedCaller.calleeOf!.count, 0) - + try await loadedCallee.callerOf?.fetch() XCTAssertEqual(loadedCallee.callerOf!.count, 0) - + try await loadedCallee.calleeOf?.fetch() XCTAssertEqual(loadedCallee.calleeOf!.count, 1) } - + func testUpdatePhoneCallToTranscript() async throws { await setup(withModels: PhoneCallModels()) let caller = Person(name: "caller") @@ -138,23 +148,23 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { XCTAssertNil(savedPhoneCall.phoneCallTranscriptId) let transcript = Transcript(text: "text", phoneCall: phoneCall) let savedTranscript = try await createAndWaitForSync(transcript) - - + + var queriedPhoneCall = try await query(for: savedPhoneCall) queriedPhoneCall.phoneCallTranscriptId = transcript.id let updatedPhoneCall = try await updateAndWaitForSync(queriedPhoneCall) XCTAssertEqual(updatedPhoneCall.phoneCallTranscriptId, transcript.id) } - + func testDeletePerson() async throws { await setup(withModels: PhoneCallModels()) let person = Person(name: "name") let savedPerson = try await createAndWaitForSync(person) - + try await deleteAndWaitForSync(savedPerson) try await assertModelDoesNotExist(savedPerson) } - + /// Deleting a PhoneCall is successful /// /// - Given: PhoneCall, belongs to two Persons @@ -171,12 +181,12 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { let savedCallee = try await createAndWaitForSync(callee) let phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let savedPhoneCall = try await createAndWaitForSync(phoneCall) - + try await deleteAndWaitForSync(savedPhoneCall) try await assertModelExists(caller) try await assertModelExists(callee) } - + /// Delete a Person with PhoneCall will delete the PhoneCall as well, cascade delete the Person's hasMany /// /// - Given: PhoneCall which belongs to two different Persons (caller and callee) @@ -194,13 +204,13 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { let savedCallee = try await createAndWaitForSync(callee) let phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let savedPhoneCall = try await createAndWaitForSync(phoneCall) - + try await deleteAndWaitForSync(savedCaller) try await assertModelDoesNotExist(savedCaller) try await assertModelDoesNotExist(savedPhoneCall) try await assertModelExists(savedCallee) } - + /// Delete Transcript does not delete its belongs-to PhoneCall /// /// - Given: Transcript belongs to a PhoneCall @@ -219,15 +229,15 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { var phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let transcript = Transcript(text: "text", phoneCall: phoneCall) phoneCall.phoneCallTranscriptId = transcript.id - + let savedPhoneCall = try await createAndWaitForSync(phoneCall) let savedTranscript = try await createAndWaitForSync(transcript) - + try await deleteAndWaitForSync(transcript) try await assertModelDoesNotExist(transcript) try await assertModelExists(phoneCall) } - + /// Deleting a PhoneCall cascades to the hasOne Transcript /// /// - Given: PhoneCall with Transcript @@ -245,10 +255,10 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { var phoneCall = PhoneCall(caller: savedCaller, callee: savedCallee) let transcript = Transcript(text: "text", phoneCall: phoneCall) phoneCall.phoneCallTranscriptId = transcript.id - + let savedPhoneCall = try await createAndWaitForSync(phoneCall) let savedTranscript = try await createAndWaitForSync(transcript) - + try await deleteAndWaitForSync(savedPhoneCall) try await assertModelDoesNotExist(savedPhoneCall) try await assertModelDoesNotExist(savedTranscript) @@ -256,7 +266,7 @@ class AWSDataStoreLazyLoadPhoneCallTests: AWSDataStoreLazyLoadBaseTest { } extension AWSDataStoreLazyLoadPhoneCallTests { - + struct PhoneCallModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person+Schema.swift index 28bef917e2..52d8a37214 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Person { +public extension Person { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case callerOf @@ -12,19 +19,19 @@ extension Person { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let person = Person.keys - + model.pluralName = "People" - + model.attributes( .primaryKey(fields: [person.id]) ) - + model.fields( .field(person.id, is: .required, ofType: .string), .field(person.name, is: .required, ofType: .string), @@ -36,32 +43,32 @@ extension Person { .field(person.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Person: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Person { - public var id: FieldPath { +public extension ModelPath where ModelType == Person { + var id: FieldPath { string("id") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var callerOf: ModelPath { + var callerOf: ModelPath { PhoneCall.Path(name: "callerOf", isCollection: true, parent: self) } - public var calleeOf: ModelPath { + var calleeOf: ModelPath { PhoneCall.Path(name: "calleeOf", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person.swift index f3d6c1328a..7b577b70b5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Person.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Person: Model { public var calleeOf: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - callerOf: List = [], - calleeOf: List = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + callerOf: List = [], + calleeOf: List = [] + ) { + self.init( + id: id, name: name, callerOf: callerOf, calleeOf: calleeOf, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - callerOf: List = [], - calleeOf: List = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + callerOf: List = [], + calleeOf: List = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.callerOf = callerOf diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall+Schema.swift index 557468c4c4..6f2522afe1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PhoneCall { +public extension PhoneCall { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case caller case callee @@ -13,21 +20,21 @@ extension PhoneCall { case updatedAt case phoneCallTranscriptId } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let phoneCall = PhoneCall.keys - + model.pluralName = "PhoneCalls" - + model.attributes( .index(fields: ["callerId"], name: "byCaller"), .index(fields: ["calleeId"], name: "byCallee"), .primaryKey(fields: [phoneCall.id]) ) - + model.fields( .field(phoneCall.id, is: .required, ofType: .string), .belongsTo(phoneCall.caller, is: .required, ofType: Person.self, targetNames: ["callerId"]), @@ -38,35 +45,35 @@ extension PhoneCall { .field(phoneCall.phoneCallTranscriptId, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PhoneCall: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == PhoneCall { - public var id: FieldPath { +public extension ModelPath where ModelType == PhoneCall { + var id: FieldPath { string("id") } - public var caller: ModelPath { + var caller: ModelPath { Person.Path(name: "caller", parent: self) } - public var callee: ModelPath { + var callee: ModelPath { Person.Path(name: "callee", parent: self) } - public var transcript: ModelPath { + var transcript: ModelPath { Transcript.Path(name: "transcript", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } - public var phoneCallTranscriptId: FieldPath { + var phoneCallTranscriptId: FieldPath { string("phoneCallTranscriptId") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall.swift index 54ebec566c..723b4cb393 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/PhoneCall.swift @@ -1,22 +1,29 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation public struct PhoneCall: Model { public let id: String - internal var _caller: LazyReference + var _caller: LazyReference public var caller: Person { get async throws { try await _caller.require() } } - internal var _callee: LazyReference + var _callee: LazyReference public var callee: Person { get async throws { try await _callee.require() } } - internal var _transcript: LazyReference + var _transcript: LazyReference public var transcript: Transcript? { get async throws { try await _transcript.get() @@ -25,27 +32,33 @@ public struct PhoneCall: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? public var phoneCallTranscriptId: String? - - public init(id: String = UUID().uuidString, - caller: Person, - callee: Person, - transcript: Transcript? = nil, - phoneCallTranscriptId: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + caller: Person, + callee: Person, + transcript: Transcript? = nil, + phoneCallTranscriptId: String? = nil + ) { + self.init( + id: id, caller: caller, callee: callee, transcript: transcript, createdAt: nil, updatedAt: nil, - phoneCallTranscriptId: phoneCallTranscriptId) + phoneCallTranscriptId: phoneCallTranscriptId + ) } - internal init(id: String = UUID().uuidString, - caller: Person, - callee: Person, - transcript: Transcript? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - phoneCallTranscriptId: String? = nil) { + init( + id: String = UUID().uuidString, + caller: Person, + callee: Person, + transcript: Transcript? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + phoneCallTranscriptId: String? = nil + ) { self.id = id self._caller = LazyReference(caller) self._callee = LazyReference(callee) @@ -55,23 +68,23 @@ public struct PhoneCall: Model { self.phoneCallTranscriptId = phoneCallTranscriptId } public mutating func setCaller(_ caller: Person) { - self._caller = LazyReference(caller) + _caller = LazyReference(caller) } public mutating func setCallee(_ callee: Person) { - self._callee = LazyReference(callee) + _callee = LazyReference(callee) } public mutating func setTranscript(_ transcript: Transcript? = nil) { - self._transcript = LazyReference(transcript) + _transcript = LazyReference(transcript) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - _caller = try values.decodeIfPresent(LazyReference.self, forKey: .caller) ?? LazyReference(identifiers: nil) - _callee = try values.decodeIfPresent(LazyReference.self, forKey: .callee) ?? LazyReference(identifiers: nil) - _transcript = try values.decodeIfPresent(LazyReference.self, forKey: .transcript) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - phoneCallTranscriptId = try? values.decode(String?.self, forKey: .phoneCallTranscriptId) + self.id = try values.decode(String.self, forKey: .id) + self._caller = try values.decodeIfPresent(LazyReference.self, forKey: .caller) ?? LazyReference(identifiers: nil) + self._callee = try values.decodeIfPresent(LazyReference.self, forKey: .callee) ?? LazyReference(identifiers: nil) + self._transcript = try values.decodeIfPresent(LazyReference.self, forKey: .transcript) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.phoneCallTranscriptId = try? values.decode(String?.self, forKey: .phoneCallTranscriptId) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript+Schema.swift index 7bffc18bdb..7c600943a4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Transcript { +public extension Transcript { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case text case language @@ -12,19 +19,19 @@ extension Transcript { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let transcript = Transcript.keys - + model.pluralName = "Transcripts" - + model.attributes( .primaryKey(fields: [transcript.id]) ) - + model.fields( .field(transcript.id, is: .required, ofType: .string), .field(transcript.text, is: .required, ofType: .string), @@ -34,32 +41,32 @@ extension Transcript { .field(transcript.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Transcript: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Transcript { - public var id: FieldPath { +public extension ModelPath where ModelType == Transcript { + var id: FieldPath { string("id") } - public var text: FieldPath { + var text: FieldPath { string("text") } - public var language: FieldPath { + var language: FieldPath { string("language") } - public var phoneCall: ModelPath { + var phoneCall: ModelPath { PhoneCall.Path(name: "phoneCall", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript.swift index 039f461e5b..4144fd8b5b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL13/Transcript.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,7 +13,7 @@ public struct Transcript: Model { public let id: String public var text: String public var language: String? - internal var _phoneCall: LazyReference + var _phoneCall: LazyReference public var phoneCall: PhoneCall? { get async throws { try await _phoneCall.get() @@ -14,24 +21,30 @@ public struct Transcript: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - text: String, - language: String? = nil, - phoneCall: PhoneCall? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + text: String, + language: String? = nil, + phoneCall: PhoneCall? = nil + ) { + self.init( + id: id, text: text, language: language, phoneCall: phoneCall, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - text: String, - language: String? = nil, - phoneCall: PhoneCall? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + text: String, + language: String? = nil, + phoneCall: PhoneCall? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.text = text self.language = language @@ -40,16 +53,16 @@ public struct Transcript: Model { self.updatedAt = updatedAt } public mutating func setPhoneCall(_ phoneCall: PhoneCall? = nil) { - self._phoneCall = LazyReference(phoneCall) + _phoneCall = LazyReference(phoneCall) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - text = try values.decode(String.self, forKey: .text) - language = try? values.decode(String?.self, forKey: .language) - _phoneCall = try values.decodeIfPresent(LazyReference.self, forKey: .phoneCall) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.text = try values.decode(String.self, forKey: .text) + self.language = try? values.decode(String?.self, forKey: .language) + self._phoneCall = try values.decodeIfPresent(LazyReference.self, forKey: .phoneCall) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentSnapshotTests.swift index 4ea8a63364..aaac3ce762 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentSnapshotTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify extension AWSDataStoreLazyLoadUserPostCommentTests { - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentTests.swift index 11bd00c7e3..267aa5f098 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/AWSDataStoreLazyLoadUserPostCommentTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @@ -23,16 +23,16 @@ final class AWSDataStoreLazyLoadUserPostCommentTests: AWSDataStoreLazyLoadBaseTe let user = User(username: "name") try await createAndWaitForSync(user) } - + func testSaveUserSettings() async throws { await setup(withModels: UserPostCommentModels()) let user = User(username: "name") let savedUser = try await createAndWaitForSync(user) - + let userSettings = UserSettings(language: "en-us", user: savedUser) try await createAndWaitForSync(userSettings) } - + func testSavePost() async throws { await setup(withModels: UserPostCommentModels()) let user = User(username: "name") @@ -40,7 +40,7 @@ final class AWSDataStoreLazyLoadUserPostCommentTests: AWSDataStoreLazyLoadBaseTe let post = Post(title: "title", rating: 1, status: .active, author: savedUser) try await createAndWaitForSync(post) } - + func testSaveComment() async throws { await setup(withModels: UserPostCommentModels()) let user = User(username: "name") @@ -50,7 +50,7 @@ final class AWSDataStoreLazyLoadUserPostCommentTests: AWSDataStoreLazyLoadBaseTe let comment = Comment(content: "content", post: savedPost, author: savedUser) try await createAndWaitForSync(comment) } - + /// LazyLoad from queried models /// /// - Given: Saved and synced models @@ -69,7 +69,7 @@ final class AWSDataStoreLazyLoadUserPostCommentTests: AWSDataStoreLazyLoadBaseTe let savedPost = try await createAndWaitForSync(post) let comment = Comment(content: "content", post: savedPost, author: savedUser) try await createAndWaitForSync(comment) - + // Traverse from User let queriedUser = try await query(for: user) try await queriedUser.posts?.fetch() @@ -79,26 +79,26 @@ final class AWSDataStoreLazyLoadUserPostCommentTests: AWSDataStoreLazyLoadBaseTe // Cannot traverse from User to settings //let queriedUserSettings = try await queriedUser.settings //XCTAssertNotNil(queriedUserSettings) - + // Traverse from UserSettings let queriedSettings = try await query(for: userSettings) let queriedSettingsUser = try await queriedSettings.user XCTAssertEqual(queriedSettingsUser.id, user.id) - + // Traverse from Post let queriedPost = try await query(for: post) try await queriedPost.comments?.fetch() XCTAssertEqual(queriedPost.comments?.count, 1) let queriedPostUser = try await queriedPost.author XCTAssertEqual(queriedPostUser.id, user.id) - + // Traverse from Comment let queriedComment = try await query(for: comment) let queriedCommentPost = try await queriedComment.post XCTAssertEqual(queriedCommentPost?.id, post.id) let queriedCommentUser = try await queriedComment.author XCTAssertEqual(queriedCommentUser.id, user.id) - + // Clean up - delete the saved models try await deleteAndWaitForSync(user) try await assertModelDoesNotExist(comment) @@ -114,7 +114,7 @@ extension AWSDataStoreLazyLoadUserPostCommentTests { typealias Post = Post14 typealias Comment = Comment14 typealias UserSettings = UserSettings14 - + struct UserPostCommentModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14+Schema.swift index 1b6f96354c..266463d581 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case content case post @@ -12,23 +19,23 @@ extension Comment14 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment14 = Comment14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Comment14s" - + model.attributes( .primaryKey(fields: [comment14.id]) ) - + model.fields( .field(comment14.id, is: .required, ofType: .string), .field(comment14.content, is: .optional, ofType: .string), @@ -38,32 +45,32 @@ extension Comment14 { .field(comment14.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Comment14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Comment14 { + var id: FieldPath { + string("id") } - public var content: FieldPath { - string("content") + var content: FieldPath { + string("content") } - public var post: ModelPath { - Post14.Path(name: "post", parent: self) + var post: ModelPath { + Post14.Path(name: "post", parent: self) } - public var author: ModelPath { - User14.Path(name: "author", parent: self) + var author: ModelPath { + User14.Path(name: "author", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14.swift index cab42a6f0d..906b61dbe6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Comment14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,38 +12,44 @@ import Foundation public struct Comment14: Model { public let id: String public var content: String? - internal var _post: LazyReference + var _post: LazyReference public var post: Post14? { - get async throws { + get async throws { try await _post.get() - } + } } - internal var _author: LazyReference + var _author: LazyReference public var author: User14 { - get async throws { + get async throws { try await _author.require() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post14? = nil, - author: User14) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post14? = nil, + author: User14 + ) { + self.init( + id: id, content: content, post: post, author: author, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post14? = nil, - author: User14, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post14? = nil, + author: User14, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -45,19 +58,19 @@ public struct Comment14: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post14? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public mutating func setAuthor(_ author: User14) { - self._author = LazyReference(author) + _author = LazyReference(author) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try? values.decode(String?.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - _author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try? values.decode(String?.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self._author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -68,4 +81,4 @@ public struct Comment14: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14+Schema.swift index bf1baaa6c2..a9f698c3ef 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case rating @@ -14,23 +21,23 @@ extension Post14 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post14 = Post14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Post14s" - + model.attributes( .primaryKey(fields: [post14.id]) ) - + model.fields( .field(post14.id, is: .required, ofType: .string), .field(post14.title, is: .required, ofType: .string), @@ -42,35 +49,35 @@ extension Post14 { .field(post14.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Post14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == Post14 { + var id: FieldPath { + string("id") } - public var title: FieldPath { - string("title") + var title: FieldPath { + string("title") } - public var rating: FieldPath { - int("rating") + var rating: FieldPath { + int("rating") } - public var comments: ModelPath { - Comment14.Path(name: "comments", isCollection: true, parent: self) + var comments: ModelPath { + Comment14.Path(name: "comments", isCollection: true, parent: self) } - public var author: ModelPath { - User14.Path(name: "author", parent: self) + var author: ModelPath { + User14.Path(name: "author", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14.swift index 42d308e637..c290b4e22e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/Post14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,38 +15,44 @@ public struct Post14: Model { public var rating: Int public var status: PostStatus public var comments: List? - internal var _author: LazyReference + var _author: LazyReference public var author: User14 { - get async throws { + get async throws { try await _author.require() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - rating: Int, - status: PostStatus, - comments: List? = [], - author: User14) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + rating: Int, + status: PostStatus, + comments: List? = [], + author: User14 + ) { + self.init( + id: id, title: title, rating: rating, status: status, comments: comments, author: author, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - rating: Int, - status: PostStatus, - comments: List? = [], - author: User14, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + rating: Int, + status: PostStatus, + comments: List? = [], + author: User14, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.rating = rating @@ -50,18 +63,18 @@ public struct Post14: Model { self.updatedAt = updatedAt } public mutating func setAuthor(_ author: User14) { - self._author = LazyReference(author) + _author = LazyReference(author) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - title = try values.decode(String.self, forKey: .title) - rating = try values.decode(Int.self, forKey: .rating) - status = try values.decode(PostStatus.self, forKey: .status) - comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() - _author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.title = try values.decode(String.self, forKey: .title) + self.rating = try values.decode(Int.self, forKey: .rating) + self.status = try values.decode(PostStatus.self, forKey: .status) + self.comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() + self._author = try values.decodeIfPresent(LazyReference.self, forKey: .author) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -74,4 +87,4 @@ public struct Post14: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/PostStatus.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/PostStatus.swift index 47329501d1..39a6c7f3e4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/PostStatus.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/PostStatus.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public enum PostStatus: String, EnumPersistable { case active = "ACTIVE" case inactive = "INACTIVE" -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14+Schema.swift index c9249873eb..20e2acd13b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension User14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension User14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case username case posts @@ -14,23 +21,23 @@ extension User14 { case updatedAt case user14SettingsId } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let user14 = User14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "User14s" - + model.attributes( .primaryKey(fields: [user14.id]) ) - + model.fields( .field(user14.id, is: .required, ofType: .string), .field(user14.username, is: .required, ofType: .string), @@ -42,38 +49,38 @@ extension User14 { .field(user14.user14SettingsId, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension User14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == User14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == User14 { + var id: FieldPath { + string("id") } - public var username: FieldPath { - string("username") + var username: FieldPath { + string("username") } - public var posts: ModelPath { - Post14.Path(name: "posts", isCollection: true, parent: self) + var posts: ModelPath { + Post14.Path(name: "posts", isCollection: true, parent: self) } - public var comments: ModelPath { - Comment14.Path(name: "comments", isCollection: true, parent: self) + var comments: ModelPath { + Comment14.Path(name: "comments", isCollection: true, parent: self) } - public var settings: ModelPath { - UserSettings14.Path(name: "settings", parent: self) + var settings: ModelPath { + UserSettings14.Path(name: "settings", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } - public var user14SettingsId: FieldPath { - string("user14SettingsId") + var user14SettingsId: FieldPath { + string("user14SettingsId") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14.swift index b65799b382..7e075a3776 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/User14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,39 +14,45 @@ public struct User14: Model { public var username: String public var posts: List? public var comments: List? - internal var _settings: LazyReference + var _settings: LazyReference public var settings: UserSettings14? { - get async throws { + get async throws { try await _settings.get() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? public var user14SettingsId: String? - - public init(id: String = UUID().uuidString, - username: String, - posts: List? = [], - comments: List? = [], - settings: UserSettings14? = nil, - user14SettingsId: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + username: String, + posts: List? = [], + comments: List? = [], + settings: UserSettings14? = nil, + user14SettingsId: String? = nil + ) { + self.init( + id: id, username: username, posts: posts, comments: comments, settings: settings, createdAt: nil, updatedAt: nil, - user14SettingsId: user14SettingsId) + user14SettingsId: user14SettingsId + ) } - internal init(id: String = UUID().uuidString, - username: String, - posts: List? = [], - comments: List? = [], - settings: UserSettings14? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - user14SettingsId: String? = nil) { + init( + id: String = UUID().uuidString, + username: String, + posts: List? = [], + comments: List? = [], + settings: UserSettings14? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + user14SettingsId: String? = nil + ) { self.id = id self.username = username self.posts = posts @@ -50,18 +63,18 @@ public struct User14: Model { self.user14SettingsId = user14SettingsId } public mutating func setSettings(_ settings: UserSettings14? = nil) { - self._settings = LazyReference(settings) + _settings = LazyReference(settings) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - username = try values.decode(String.self, forKey: .username) - posts = try values.decodeIfPresent(List?.self, forKey: .posts) ?? .init() - comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() - _settings = try values.decodeIfPresent(LazyReference.self, forKey: .settings) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - user14SettingsId = try? values.decode(String?.self, forKey: .user14SettingsId) + self.id = try values.decode(String.self, forKey: .id) + self.username = try values.decode(String.self, forKey: .username) + self.posts = try values.decodeIfPresent(List?.self, forKey: .posts) ?? .init() + self.comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() + self._settings = try values.decodeIfPresent(LazyReference.self, forKey: .settings) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.user14SettingsId = try? values.decode(String?.self, forKey: .user14SettingsId) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -74,4 +87,4 @@ public struct User14: Model { try container.encode(updatedAt, forKey: .updatedAt) try container.encode(user14SettingsId, forKey: .user14SettingsId) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14+Schema.swift index 1bc8bcd441..2e8f1dfa0a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14+Schema.swift @@ -1,33 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension UserSettings14 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension UserSettings14 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case language case user case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let userSettings14 = UserSettings14.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "UserSettings14s" - + model.attributes( .primaryKey(fields: [userSettings14.id]) ) - + model.fields( .field(userSettings14.id, is: .required, ofType: .string), .field(userSettings14.language, is: .optional, ofType: .string), @@ -36,29 +43,29 @@ extension UserSettings14 { .field(userSettings14.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension UserSettings14: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == UserSettings14 { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == UserSettings14 { + var id: FieldPath { + string("id") } - public var language: FieldPath { - string("language") + var language: FieldPath { + string("language") } - public var user: ModelPath { - User14.Path(name: "user", parent: self) + var user: ModelPath { + User14.Path(name: "user", parent: self) } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14.swift index b0e8cbf0ff..6cc8ae97ae 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL14/UserSettings14.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,29 +12,35 @@ import Foundation public struct UserSettings14: Model { public let id: String public var language: String? - internal var _user: LazyReference + var _user: LazyReference public var user: User14 { - get async throws { + get async throws { try await _user.require() - } + } } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - language: String? = nil, - user: User14) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + language: String? = nil, + user: User14 + ) { + self.init( + id: id, language: language, user: user, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - language: String? = nil, - user: User14, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + language: String? = nil, + user: User14, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.language = language self._user = LazyReference(user) @@ -35,15 +48,15 @@ public struct UserSettings14: Model { self.updatedAt = updatedAt } public mutating func setUser(_ user: User14) { - self._user = LazyReference(user) + _user = LazyReference(user) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - language = try? values.decode(String?.self, forKey: .language) - _user = try values.decodeIfPresent(LazyReference.self, forKey: .user) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.language = try? values.decode(String?.self, forKey: .language) + self._user = try values.decodeIfPresent(LazyReference.self, forKey: .user) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) @@ -53,4 +66,4 @@ public struct UserSettings14: Model { try container.encode(createdAt, forKey: .createdAt) try container.encode(updatedAt, forKey: .updatedAt) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel+Schema.swift index 654c541c4a..a93f3181c2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension EnumTestModel { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension EnumTestModel { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case enumVal case nullableEnumVal @@ -15,19 +22,19 @@ extension EnumTestModel { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let enumTestModel = EnumTestModel.keys - + model.pluralName = "EnumTestModels" - + model.attributes( .primaryKey(fields: [enumTestModel.id]) ) - + model.fields( .field(enumTestModel.id, is: .required, ofType: .string), .field(enumTestModel.enumVal, is: .required, ofType: .enum(type: TestEnum.self)), @@ -40,23 +47,23 @@ extension EnumTestModel { .field(enumTestModel.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension EnumTestModel: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == EnumTestModel { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == EnumTestModel { + var id: FieldPath { + string("id") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel.swift index 57a45cd219..de9368dd4d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/EnumTestModel.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct EnumTestModel: Model { public var nullableEnumNullableList: [TestEnum?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - enumVal: TestEnum, - nullableEnumVal: TestEnum? = nil, - enumList: [TestEnum] = [], - enumNullableList: [TestEnum]? = nil, - nullableEnumList: [TestEnum?] = [], - nullableEnumNullableList: [TestEnum?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + enumVal: TestEnum, + nullableEnumVal: TestEnum? = nil, + enumList: [TestEnum] = [], + enumNullableList: [TestEnum]? = nil, + nullableEnumList: [TestEnum?] = [], + nullableEnumNullableList: [TestEnum?]? = nil + ) { + self.init( + id: id, enumVal: enumVal, nullableEnumVal: nullableEnumVal, enumList: enumList, @@ -28,17 +38,20 @@ public struct EnumTestModel: Model { nullableEnumList: nullableEnumList, nullableEnumNullableList: nullableEnumNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - enumVal: TestEnum, - nullableEnumVal: TestEnum? = nil, - enumList: [TestEnum] = [], - enumNullableList: [TestEnum]? = nil, - nullableEnumList: [TestEnum?] = [], - nullableEnumNullableList: [TestEnum?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + enumVal: TestEnum, + nullableEnumVal: TestEnum? = nil, + enumList: [TestEnum] = [], + enumNullableList: [TestEnum]? = nil, + nullableEnumList: [TestEnum?] = [], + nullableEnumNullableList: [TestEnum?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.enumVal = enumVal self.nullableEnumVal = nullableEnumVal @@ -49,4 +62,4 @@ public struct EnumTestModel: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer+Schema.swift index 45a99508b6..77b79afd91 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ListIntContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ListIntContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case test case nullableInt @@ -15,19 +22,19 @@ extension ListIntContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let listIntContainer = ListIntContainer.keys - + model.pluralName = "ListIntContainers" - + model.attributes( .primaryKey(fields: [listIntContainer.id]) ) - + model.fields( .field(listIntContainer.id, is: .required, ofType: .string), .field(listIntContainer.test, is: .required, ofType: .int), @@ -40,41 +47,41 @@ extension ListIntContainer { .field(listIntContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ListIntContainer: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == ListIntContainer { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == ListIntContainer { + var id: FieldPath { + string("id") } - public var test: FieldPath { - int("test") + var test: FieldPath { + int("test") } - public var nullableInt: FieldPath { - int("nullableInt") + var nullableInt: FieldPath { + int("nullableInt") } - public var intList: FieldPath { - int("intList") + var intList: FieldPath { + int("intList") } - public var intNullableList: FieldPath { - int("intNullableList") + var intNullableList: FieldPath { + int("intNullableList") } - public var nullableIntList: FieldPath { - int("nullableIntList") + var nullableIntList: FieldPath { + int("nullableIntList") } - public var nullableIntNullableList: FieldPath { - int("nullableIntNullableList") + var nullableIntNullableList: FieldPath { + int("nullableIntNullableList") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer.swift index 040edd16e8..efb53081d8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListIntContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct ListIntContainer: Model { public var nullableIntNullableList: [Int?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - test: Int, - nullableInt: Int? = nil, - intList: [Int] = [], - intNullableList: [Int]? = nil, - nullableIntList: [Int?] = [], - nullableIntNullableList: [Int?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + test: Int, + nullableInt: Int? = nil, + intList: [Int] = [], + intNullableList: [Int]? = nil, + nullableIntList: [Int?] = [], + nullableIntNullableList: [Int?]? = nil + ) { + self.init( + id: id, test: test, nullableInt: nullableInt, intList: intList, @@ -28,17 +38,20 @@ public struct ListIntContainer: Model { nullableIntList: nullableIntList, nullableIntNullableList: nullableIntNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - test: Int, - nullableInt: Int? = nil, - intList: [Int] = [], - intNullableList: [Int]? = nil, - nullableIntList: [Int?] = [], - nullableIntNullableList: [Int?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + test: Int, + nullableInt: Int? = nil, + intList: [Int] = [], + intNullableList: [Int]? = nil, + nullableIntList: [Int?] = [], + nullableIntNullableList: [Int?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.test = test self.nullableInt = nullableInt @@ -49,4 +62,4 @@ public struct ListIntContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer+Schema.swift index 151cfaf8c7..505e667481 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ListStringContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ListStringContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case test case nullableString @@ -15,19 +22,19 @@ extension ListStringContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let listStringContainer = ListStringContainer.keys - + model.pluralName = "ListStringContainers" - + model.attributes( .primaryKey(fields: [listStringContainer.id]) ) - + model.fields( .field(listStringContainer.id, is: .required, ofType: .string), .field(listStringContainer.test, is: .required, ofType: .string), @@ -40,41 +47,41 @@ extension ListStringContainer { .field(listStringContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ListStringContainer: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == ListStringContainer { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == ListStringContainer { + var id: FieldPath { + string("id") } - public var test: FieldPath { - string("test") + var test: FieldPath { + string("test") } - public var nullableString: FieldPath { - string("nullableString") + var nullableString: FieldPath { + string("nullableString") } - public var stringList: FieldPath { - string("stringList") + var stringList: FieldPath { + string("stringList") } - public var stringNullableList: FieldPath { - string("stringNullableList") + var stringNullableList: FieldPath { + string("stringNullableList") } - public var nullableStringList: FieldPath { - string("nullableStringList") + var nullableStringList: FieldPath { + string("nullableStringList") } - public var nullableStringNullableList: FieldPath { - string("nullableStringNullableList") + var nullableStringNullableList: FieldPath { + string("nullableStringNullableList") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer.swift index cfe1107366..d08e28aa86 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ListStringContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct ListStringContainer: Model { public var nullableStringNullableList: [String?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - test: String, - nullableString: String? = nil, - stringList: [String] = [], - stringNullableList: [String]? = nil, - nullableStringList: [String?] = [], - nullableStringNullableList: [String?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + test: String, + nullableString: String? = nil, + stringList: [String] = [], + stringNullableList: [String]? = nil, + nullableStringList: [String?] = [], + nullableStringNullableList: [String?]? = nil + ) { + self.init( + id: id, test: test, nullableString: nullableString, stringList: stringList, @@ -28,17 +38,20 @@ public struct ListStringContainer: Model { nullableStringList: nullableStringList, nullableStringNullableList: nullableStringNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - test: String, - nullableString: String? = nil, - stringList: [String] = [], - stringNullableList: [String]? = nil, - nullableStringList: [String?] = [], - nullableStringNullableList: [String?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + test: String, + nullableString: String? = nil, + stringList: [String] = [], + stringNullableList: [String]? = nil, + nullableStringList: [String?] = [], + nullableStringNullableList: [String?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.test = test self.nullableString = nullableString @@ -49,4 +62,4 @@ public struct ListStringContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested+Schema.swift index 1c83d051d7..d2cd8eeea4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested+Schema.swift @@ -1,25 +1,32 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Nested { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Nested { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case valueOne case valueTwo } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let nested = Nested.keys - + model.pluralName = "Nesteds" - + model.fields( .field(nested.valueOne, is: .optional, ofType: .int), .field(nested.valueTwo, is: .optional, ofType: .string) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested.swift index 37415d4550..19da9762a3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/Nested.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public struct Nested: Embeddable { var valueOne: Int? var valueTwo: String? -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift index a01c7c3046..e92577edf2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension NestedTypeTestModel { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension NestedTypeTestModel { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case nestedVal case nullableNestedVal @@ -15,19 +22,19 @@ extension NestedTypeTestModel { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let nestedTypeTestModel = NestedTypeTestModel.keys - + model.pluralName = "NestedTypeTestModels" - + model.attributes( .primaryKey(fields: [nestedTypeTestModel.id]) ) - + model.fields( .field(nestedTypeTestModel.id, is: .required, ofType: .string), .field(nestedTypeTestModel.nestedVal, is: .required, ofType: .embedded(type: Nested.self)), @@ -40,23 +47,23 @@ extension NestedTypeTestModel { .field(nestedTypeTestModel.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension NestedTypeTestModel: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == NestedTypeTestModel { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == NestedTypeTestModel { + var id: FieldPath { + string("id") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel.swift index 2167581607..bd5c875239 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/NestedTypeTestModel.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -12,15 +19,18 @@ public struct NestedTypeTestModel: Model { public var nullableNestedNullableList: [Nested?]? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - nestedVal: Nested, - nullableNestedVal: Nested? = nil, - nestedList: [Nested] = [], - nestedNullableList: [Nested]? = nil, - nullableNestedList: [Nested?] = [], - nullableNestedNullableList: [Nested?]? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + nestedVal: Nested, + nullableNestedVal: Nested? = nil, + nestedList: [Nested] = [], + nestedNullableList: [Nested]? = nil, + nullableNestedList: [Nested?] = [], + nullableNestedNullableList: [Nested?]? = nil + ) { + self.init( + id: id, nestedVal: nestedVal, nullableNestedVal: nullableNestedVal, nestedList: nestedList, @@ -28,17 +38,20 @@ public struct NestedTypeTestModel: Model { nullableNestedList: nullableNestedList, nullableNestedNullableList: nullableNestedNullableList, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - nestedVal: Nested, - nullableNestedVal: Nested? = nil, - nestedList: [Nested] = [], - nestedNullableList: [Nested]? = nil, - nullableNestedList: [Nested?] = [], - nullableNestedNullableList: [Nested?]? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + nestedVal: Nested, + nullableNestedVal: Nested? = nil, + nestedList: [Nested] = [], + nestedNullableList: [Nested]? = nil, + nullableNestedList: [Nested?] = [], + nullableNestedNullableList: [Nested?]? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.nestedVal = nestedVal self.nullableNestedVal = nullableNestedVal @@ -49,4 +62,4 @@ public struct NestedTypeTestModel: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer+Schema.swift index a4db044062..0af1b206bc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension ScalarContainer { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension ScalarContainer { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case myString case myInt @@ -22,19 +29,19 @@ extension ScalarContainer { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let scalarContainer = ScalarContainer.keys - + model.pluralName = "ScalarContainers" - + model.attributes( .primaryKey(fields: [scalarContainer.id]) ) - + model.fields( .field(scalarContainer.id, is: .required, ofType: .string), .field(scalarContainer.myString, is: .optional, ofType: .string), @@ -54,62 +61,62 @@ extension ScalarContainer { .field(scalarContainer.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension ScalarContainer: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == ScalarContainer { - public var id: FieldPath { - string("id") +public extension ModelPath where ModelType == ScalarContainer { + var id: FieldPath { + string("id") } - public var myString: FieldPath { - string("myString") + var myString: FieldPath { + string("myString") } - public var myInt: FieldPath { - int("myInt") + var myInt: FieldPath { + int("myInt") } - public var myDouble: FieldPath { - double("myDouble") + var myDouble: FieldPath { + double("myDouble") } - public var myBool: FieldPath { - bool("myBool") + var myBool: FieldPath { + bool("myBool") } - public var myDate: FieldPath { - date("myDate") + var myDate: FieldPath { + date("myDate") } - public var myTime: FieldPath { - time("myTime") + var myTime: FieldPath { + time("myTime") } - public var myDateTime: FieldPath { - datetime("myDateTime") + var myDateTime: FieldPath { + datetime("myDateTime") } - public var myTimeStamp: FieldPath { - int("myTimeStamp") + var myTimeStamp: FieldPath { + int("myTimeStamp") } - public var myEmail: FieldPath { - string("myEmail") + var myEmail: FieldPath { + string("myEmail") } - public var myJSON: FieldPath { - string("myJSON") + var myJSON: FieldPath { + string("myJSON") } - public var myPhone: FieldPath { - string("myPhone") + var myPhone: FieldPath { + string("myPhone") } - public var myURL: FieldPath { - string("myURL") + var myURL: FieldPath { + string("myURL") } - public var myIPAddress: FieldPath { - string("myIPAddress") + var myIPAddress: FieldPath { + string("myIPAddress") } - public var createdAt: FieldPath { - datetime("createdAt") + var createdAt: FieldPath { + datetime("createdAt") } - public var updatedAt: FieldPath { - datetime("updatedAt") + var updatedAt: FieldPath { + datetime("updatedAt") } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer.swift index 9559211652..ee87c57ecd 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/ScalarContainer.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -19,22 +26,25 @@ public struct ScalarContainer: Model { public var myIPAddress: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - myString: String? = nil, - myInt: Int? = nil, - myDouble: Double? = nil, - myBool: Bool? = nil, - myDate: Temporal.Date? = nil, - myTime: Temporal.Time? = nil, - myDateTime: Temporal.DateTime? = nil, - myTimeStamp: Int? = nil, - myEmail: String? = nil, - myJSON: String? = nil, - myPhone: String? = nil, - myURL: String? = nil, - myIPAddress: String? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + myString: String? = nil, + myInt: Int? = nil, + myDouble: Double? = nil, + myBool: Bool? = nil, + myDate: Temporal.Date? = nil, + myTime: Temporal.Time? = nil, + myDateTime: Temporal.DateTime? = nil, + myTimeStamp: Int? = nil, + myEmail: String? = nil, + myJSON: String? = nil, + myPhone: String? = nil, + myURL: String? = nil, + myIPAddress: String? = nil + ) { + self.init( + id: id, myString: myString, myInt: myInt, myDouble: myDouble, @@ -49,24 +59,27 @@ public struct ScalarContainer: Model { myURL: myURL, myIPAddress: myIPAddress, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - myString: String? = nil, - myInt: Int? = nil, - myDouble: Double? = nil, - myBool: Bool? = nil, - myDate: Temporal.Date? = nil, - myTime: Temporal.Time? = nil, - myDateTime: Temporal.DateTime? = nil, - myTimeStamp: Int? = nil, - myEmail: String? = nil, - myJSON: String? = nil, - myPhone: String? = nil, - myURL: String? = nil, - myIPAddress: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + myString: String? = nil, + myInt: Int? = nil, + myDouble: Double? = nil, + myBool: Bool? = nil, + myDate: Temporal.Date? = nil, + myTime: Temporal.Time? = nil, + myDateTime: Temporal.DateTime? = nil, + myTimeStamp: Int? = nil, + myEmail: String? = nil, + myJSON: String? = nil, + myPhone: String? = nil, + myURL: String? = nil, + myIPAddress: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.myString = myString self.myInt = myInt @@ -84,4 +97,4 @@ public struct ScalarContainer: Model { self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/TestEnum.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/TestEnum.swift index 8c0fdf51ef..774eca554f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/TestEnum.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL15/TestEnum.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,4 +12,4 @@ import Foundation public enum TestEnum: String, EnumPersistable { case valueOne = "VALUE_ONE" case valueTwo = "VALUE_TWO" -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadBlogPostComment8V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadBlogPostComment8V2Tests.swift index 5d370e3d08..5839fef4fa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadBlogPostComment8V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadBlogPostComment8V2Tests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBaseTest { @@ -21,20 +21,20 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas func testSaveBlog() async throws { await setup(withModels: BlogPostComment8V2Models()) - + let blog = Blog(name: "name") let savedBlog = try await createAndWaitForSync(blog) } - + func testSavePost() async throws { await setup(withModels: BlogPostComment8V2Models()) let blog = Blog(name: "name") let post = Post(name: "name", randomId: "randomId", blog: blog) let savedBlog = try await createAndWaitForSync(blog) let savedPost = try await createAndWaitForSync(post) - + } - + func testSaveComment() async throws { await setup(withModels: BlogPostComment8V2Models()) @@ -43,7 +43,7 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) } - + func testLazyLoad() async throws { await setup(withModels: BlogPostComment8V2Models()) @@ -54,63 +54,81 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) } - - func assertComment(_ comment: Comment, - hasEagerLoaded post: Post) async throws { - assertLazyReference(comment._post, - state: .loaded(model: post)) - + + func assertComment( + _ comment: Comment, + hasEagerLoaded post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) + guard let loadedPost = try await comment.post else { XCTFail("Failed to retrieve the post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - + try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertComment(_ comment: Comment, - canLazyLoad post: Post) async throws { - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) + + func assertComment( + _ comment: Comment, + canLazyLoad post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) guard let loadedPost = try await comment.post else { XCTFail("Failed to load the post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - assertLazyReference(comment._post, - state: .loaded(model: post)) + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIds: [post.identifier], - associatedFields: ["post"])) - + assertList(comments, state: .isNotLoaded( + associatedIds: [post.identifier], + associatedFields: ["post"] + )) + try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { XCTFail("Missing lazy loaded comment from post") return } - + // further nested models should not be loaded - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) } - + func testSaveWithoutPost() async throws { await setup(withModels: BlogPostComment8V2Models()) let comment = Comment(content: "content") let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: nil) + ) let post = Post(name: "name", randomId: "randomId") let savedPost = try await createAndWaitForSync(post) queriedComment.setPost(savedPost) @@ -118,7 +136,7 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let queriedComment2 = try await query(for: saveCommentWithPost) try await assertComment(queriedComment2, canLazyLoad: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: BlogPostComment8V2Models()) let post = Post(name: "name", randomId: "randomId") @@ -126,24 +144,28 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) let queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) let savedQueriedComment = try await updateAndWaitForSync(queriedComment) let queriedComment2 = try await query(for: savedQueriedComment) try await assertComment(queriedComment2, canLazyLoad: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: BlogPostComment8V2Models()) - + let post = Post(name: "name", randomId: "randomId") let comment = Comment(content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) + let newPost = Post(name: "name") _ = try await createAndWaitForSync(newPost) queriedComment.setPost(newPost) @@ -151,28 +173,32 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let queriedComment2 = try await query(for: saveCommentWithNewPost) try await assertComment(queriedComment2, canLazyLoad: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: BlogPostComment8V2Models()) - + let post = Post(name: "name", randomId: "randomId") let comment = Comment(content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) + queriedComment.setPost(nil) let saveCommentRemovePost = try await updateAndWaitForSync(queriedComment) let queriedCommentNoPost = try await query(for: saveCommentRemovePost) - assertLazyReference(queriedCommentNoPost._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedCommentNoPost._post, + state: .notLoaded(identifiers: nil) + ) } - + func testDelete() async throws { await setup(withModels: BlogPostComment8V2Models()) - + let post = Post(name: "name", randomId: "randomId") let comment = Comment(content: "content", post: post) let savedPost = try await createAndWaitForSync(post) @@ -181,7 +207,7 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas try await assertModelDoesNotExist(savedComment) try await assertModelDoesNotExist(savedPost) } - + func testObservePost() async throws { await setup(withModels: BlogPostComment8V2Models()) try await startAndWaitForReady() @@ -195,9 +221,9 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas version == 1, let receivedPost = try? mutationEvent.decodeModel(as: Post.self), receivedPost.id == post.id { - + try await createAndWaitForSync(comment) - + guard let comments = receivedPost.comments else { XCTFail("Lazy List does not exist") return @@ -208,23 +234,23 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: BlogPostComment8V2Models()) try await startAndWaitForReady() @@ -244,18 +270,18 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: BlogPostComment8V2Models()) try await startAndWaitForReady() @@ -277,27 +303,27 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + snapshotReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: BlogPostComment8V2Models()) try await startAndWaitForReady() - + let post = Post(name: "name", randomId: "randomId") let savedPost = try await createAndWaitForSync(post) let comment = Comment(content: "content", post: post) @@ -311,14 +337,14 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -348,15 +374,19 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas for try await mutationEvent in mutationEvents { if let receivedComment = try? mutationEvent.decodeModel(as: Comment.self), receivedComment.id == receivedComment.id { - assertLazyReference(receivedComment._post, - state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)])) + assertLazyReference( + receivedComment._post, + state: .notLoaded(identifiers: [.init(name: "id", value: post.identifier)]) + ) guard let loadedPost = try await comment.post else { XCTFail("Failed to load the post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - assertLazyReference(comment._post, - state: .loaded(model: post)) + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) mutationEventReceived.fulfill() } else { XCTFail("The model should be correctly decoded") @@ -367,7 +397,8 @@ final class AWSDataStoreLazyLoadBlogPostComment8V2Tests: AWSDataStoreLazyLoadBas let deleteRequest = GraphQLRequest.deleteMutation( of: comment, modelSchema: Comment.schema, - version: 1) + version: 1 + ) do { let result = try await Amplify.API.mutate(request: deleteRequest) print(result) @@ -384,7 +415,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { typealias Blog = Blog8V2 typealias Post = Post8V2 typealias Comment = Comment8V2 - + struct BlogPostComment8V2Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadingBlogPostCmment8V2SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadingBlogPostCmment8V2SnapshotTests.swift index 9284c720e8..be5b7003b3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadingBlogPostCmment8V2SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/AWSDataStoreLazyLoadingBlogPostCmment8V2SnapshotTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { @@ -48,7 +48,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: blog, modelSchema: Blog.schema) let updateDocument = """ @@ -79,7 +79,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: blog, modelSchema: Blog.schema) let deleteDocument = """ @@ -110,7 +110,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Blog.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -141,7 +141,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Blog.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -172,7 +172,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Blog.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -203,7 +203,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Blog.self) let syncDocument = """ @@ -239,7 +239,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testPostSelectionSets() { setUpModelRegistrationOnly(withModels: BlogPostComment8V2Models()) continueAfterFailure = true @@ -285,7 +285,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -327,7 +327,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -369,7 +369,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -393,7 +393,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -417,7 +417,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -441,7 +441,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -470,13 +470,13 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: BlogPostComment8V2Models()) continueAfterFailure = true let post = Post(name: "name") let comment = Comment(content: "content", post: post) - + // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -505,7 +505,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -534,7 +534,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -563,7 +563,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -586,7 +586,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -609,7 +609,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -632,7 +632,7 @@ extension AWSDataStoreLazyLoadBlogPostComment8V2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2+Schema.swift index 04bf6c0913..cf1926979a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Blog8V2 { +public extension Blog8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case customs @@ -13,19 +20,19 @@ extension Blog8V2 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let blog8V2 = Blog8V2.keys - + model.pluralName = "Blog8V2s" - + model.attributes( .primaryKey(fields: [blog8V2.id]) ) - + model.fields( .field(blog8V2.id, is: .required, ofType: .string), .field(blog8V2.name, is: .required, ofType: .string), @@ -36,32 +43,32 @@ extension Blog8V2 { .field(blog8V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Blog8V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Blog8V2 { - public var id: FieldPath { +public extension ModelPath where ModelType == Blog8V2 { + var id: FieldPath { string("id") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var notes: FieldPath { + var notes: FieldPath { string("notes") } - public var posts: ModelPath { + var posts: ModelPath { Post8V2.Path(name: "posts", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2.swift index 53a81844ff..c317d9f8c3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Blog8V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -10,27 +17,33 @@ public struct Blog8V2: Model { public var posts: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [] + ) { + self.init( + id: id, name: name, customs: customs, notes: notes, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.customs = customs diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2+Schema.swift index 09c2b3de65..1e6ae176b2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment8V2 { +public extension Comment8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let comment8V2 = Comment8V2.keys - + model.pluralName = "Comment8V2s" - + model.attributes( .index(fields: ["postId"], name: "commentByPost"), .primaryKey(fields: [comment8V2.id]) ) - + model.fields( .field(comment8V2.id, is: .required, ofType: .string), .field(comment8V2.content, is: .optional, ofType: .string), @@ -33,29 +40,29 @@ extension Comment8V2 { .field(comment8V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment8V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Comment8V2 { - public var id: FieldPath { +public extension ModelPath where ModelType == Comment8V2 { + var id: FieldPath { string("id") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var post: ModelPath { + var post: ModelPath { Post8V2.Path(name: "post", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2.swift index ab6e1c697a..6f141be4fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Comment8V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Comment8V2: Model { public let id: String public var content: String? - internal var _post: LazyReference + var _post: LazyReference public var post: Post8V2? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct Comment8V2: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8V2? = nil) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct Comment8V2: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: Post8V2? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try? values.decode(String?.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try? values.decode(String?.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift index 2c926d8ab8..b243eec04e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8+Schema.swift @@ -1,24 +1,31 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension MyCustomModel8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension MyCustomModel8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case name case desc case children } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let myCustomModel8 = MyCustomModel8.keys - + model.pluralName = "MyCustomModel8s" - + model.fields( .field(myCustomModel8.id, is: .required, ofType: .string), .field(myCustomModel8.name, is: .required, ofType: .string), @@ -26,4 +33,4 @@ extension MyCustomModel8 { .field(myCustomModel8.children, is: .optional, ofType: .embeddedCollection(of: MyNestedModel8.self)) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8.swift index 6fb7a2b02d..152b045540 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyCustomModel8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,4 +14,4 @@ public struct MyCustomModel8: Embeddable { var name: String var desc: String? var children: [MyNestedModel8?]? -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift index da4f5f1040..871a8a25a7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8+Schema.swift @@ -1,27 +1,34 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension MyNestedModel8 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension MyNestedModel8 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case nestedName case notes } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let myNestedModel8 = MyNestedModel8.keys - + model.pluralName = "MyNestedModel8s" - + model.fields( .field(myNestedModel8.id, is: .required, ofType: .string), .field(myNestedModel8.nestedName, is: .required, ofType: .string), .field(myNestedModel8.notes, is: .optional, ofType: .embeddedCollection(of: String.self)) ) } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8.swift index 9884b8a197..6a99c2e543 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/MyNestedModel8.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,4 +13,4 @@ public struct MyNestedModel8: Embeddable { var id: String var nestedName: String var notes: [String?]? -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2+Schema.swift index b2d02ddfa0..0ea3d6a6f4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post8V2 { +public extension Post8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case randomId @@ -13,21 +20,21 @@ extension Post8V2 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let post8V2 = Post8V2.keys - + model.pluralName = "Post8V2s" - + model.attributes( .index(fields: ["blogId"], name: "postByBlog"), .index(fields: ["randomId"], name: "byRandom"), .primaryKey(fields: [post8V2.id]) ) - + model.fields( .field(post8V2.id, is: .required, ofType: .string), .field(post8V2.name, is: .required, ofType: .string), @@ -38,35 +45,35 @@ extension Post8V2 { .field(post8V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post8V2: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == Post8V2 { - public var id: FieldPath { +public extension ModelPath where ModelType == Post8V2 { + var id: FieldPath { string("id") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var randomId: FieldPath { + var randomId: FieldPath { string("randomId") } - public var blog: ModelPath { + var blog: ModelPath { Blog8V2.Path(name: "blog", parent: self) } - public var comments: ModelPath { + var comments: ModelPath { Comment8V2.Path(name: "comments", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2.swift index 7e5805afb9..9d416ecf23 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL2/Post8V2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -6,7 +13,7 @@ public struct Post8V2: Model { public let id: String public var name: String public var randomId: String? - internal var _blog: LazyReference + var _blog: LazyReference public var blog: Blog8V2? { get async throws { try await _blog.get() @@ -15,27 +22,33 @@ public struct Post8V2: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8V2? = nil, - comments: List? = []) { - self.init(id: id, - name: name, - randomId: randomId, - blog: blog, - comments: comments, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8V2? = nil, + comments: List? = [] + ) { + self.init( + id: id, + name: name, + randomId: randomId, + blog: blog, + comments: comments, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8V2? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8V2? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.randomId = randomId @@ -45,17 +58,17 @@ public struct Post8V2: Model { self.updatedAt = updatedAt } public mutating func setBlog(_ blog: Blog8V2? = nil) { - self._blog = LazyReference(blog) + _blog = LazyReference(blog) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - name = try values.decode(String.self, forKey: .name) - randomId = try? values.decode(String?.self, forKey: .randomId) - _blog = try values.decodeIfPresent(LazyReference.self, forKey: .blog) ?? LazyReference(identifiers: nil) - comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.name = try values.decode(String.self, forKey: .name) + self.randomId = try? values.decode(String?.self, forKey: .randomId) + self._blog = try values.decodeIfPresent(LazyReference.self, forKey: .blog) ?? LazyReference(identifiers: nil) + self.comments = try values.decodeIfPresent(List?.self, forKey: .comments) ?? .init() + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeySnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeySnapshotTests.swift index cc2b1f7291..f73a65a3a4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeySnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeySnapshotTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { - + func testPostSelectionSets() { setUpModelRegistrationOnly(withModels: PostCommentWithCompositeKeyModels()) continueAfterFailure = true @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -148,13 +148,13 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: PostCommentWithCompositeKeyModels()) continueAfterFailure = true let post = Post(title: "title") let comment = Comment(content: "content", post: post) - + // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -182,7 +182,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -210,7 +210,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -238,7 +238,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -262,7 +262,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -286,7 +286,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -310,7 +310,7 @@ extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests.swift index d55cd9356f..64d7ff6b3b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests.swift @@ -5,18 +5,18 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLazyLoadBaseTest { func testLazyLoad() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) let savedPost = try await createAndWaitForSync(post) @@ -28,73 +28,91 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa let queriedPost = try await query(for: savedPost) try await assertPost(queriedPost, canLazyLoad: savedComment) } - - func assertComment(_ comment: Comment, - hasEagerLoaded post: Post) async throws { - assertLazyReference(comment._post, - state: .loaded(model: post)) - + + func assertComment( + _ comment: Comment, + hasEagerLoaded post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) + guard let loadedPost = try await comment.post else { XCTFail("Failed to retrieve the post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - + // retrieve loaded model guard let loadedPost = try await comment.post else { XCTFail("Failed to retrieve the loaded post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - + try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertComment(_ comment: Comment, - canLazyLoad post: Post) async throws { - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.id.stringValue, value: post.id), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) + + func assertComment( + _ comment: Comment, + canLazyLoad post: Post + ) async throws { + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.id.stringValue, value: post.id), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) guard let loadedPost = try await comment.post else { XCTFail("Failed to load the post from the comment") return } XCTAssertEqual(loadedPost.id, post.id) - assertLazyReference(comment._post, - state: .loaded(model: post)) + assertLazyReference( + comment._post, + state: .loaded(model: post) + ) try await assertPost(loadedPost, canLazyLoad: comment) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIds: [post.identifier], - associatedFields: ["post"])) + assertList(comments, state: .isNotLoaded( + associatedIds: [post.identifier], + associatedFields: ["post"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { XCTFail("Missing lazy loaded comment from post") return } - assertLazyReference(comment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.id.stringValue, value: post.id), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) + assertLazyReference( + comment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.id.stringValue, value: post.id), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) } - + func testSaveWithoutPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let comment = Comment(content: "content") let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: nil) + ) let post = Post(title: "title") let savedPost = try await createAndWaitForSync(post) queriedComment.setPost(savedPost) @@ -102,7 +120,7 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa let queriedComment2 = try await query(for: saveCommentWithPost) try await assertComment(queriedComment2, canLazyLoad: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) let post = Post(title: "title") @@ -110,30 +128,34 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) let queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.id.stringValue, value: post.id), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.id.stringValue, value: post.id), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) let savedQueriedComment = try await updateAndWaitForSync(queriedComment) let queriedComment2 = try await query(for: savedQueriedComment) try await assertComment(queriedComment2, canLazyLoad: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.id.stringValue, value: post.id), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.id.stringValue, value: post.id), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) + let newPost = Post(title: "title") _ = try await createAndWaitForSync(newPost) queriedComment.setPost(newPost) @@ -141,31 +163,35 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa let queriedComment2 = try await query(for: saveCommentWithNewPost) try await assertComment(queriedComment2, canLazyLoad: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) - assertLazyReference(queriedComment._post, - state: .notLoaded(identifiers: [ - .init(name: Post.keys.id.stringValue, value: post.id), - .init(name: Post.keys.title.stringValue, value: post.title) - ])) - + assertLazyReference( + queriedComment._post, + state: .notLoaded(identifiers: [ + .init(name: Post.keys.id.stringValue, value: post.id), + .init(name: Post.keys.title.stringValue, value: post.title) + ]) + ) + queriedComment.setPost(nil) let saveCommentRemovePost = try await updateAndWaitForSync(queriedComment) let queriedCommentNoPost = try await query(for: saveCommentRemovePost) - assertLazyReference(queriedCommentNoPost._post, - state: .notLoaded(identifiers: nil)) + assertLazyReference( + queriedCommentNoPost._post, + state: .notLoaded(identifiers: nil) + ) } - + func testDelete() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) - + let post = Post(title: "title") let comment = Comment(content: "content", post: post) let savedPost = try await createAndWaitForSync(post) @@ -174,7 +200,7 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa try await assertModelDoesNotExist(savedComment) try await assertModelDoesNotExist(savedPost) } - + func testObservePost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) try await startAndWaitForReady() @@ -188,7 +214,7 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa version == 1, let receivedPost = try? mutationEvent.decodeModel(as: Post.self), receivedPost.id == post.id { - + try await createAndWaitForSync(comment) guard let comments = receivedPost.comments else { XCTFail("Lazy List does not exist") @@ -200,23 +226,23 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) try await startAndWaitForReady() @@ -236,18 +262,18 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) try await startAndWaitForReady() @@ -269,27 +295,27 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa XCTFail("Failed to lazy load comments \(error)") } XCTAssertEqual(comments.count, 1) - + snapshotReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: PostCommentWithCompositeKeyModels()) try await startAndWaitForReady() - + let post = Post(title: "title") let savedPost = try await createAndWaitForSync(post) let comment = Comment(content: "content", post: post) @@ -303,14 +329,14 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -319,7 +345,7 @@ final class AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests: AWSDataStoreLa extension AWSDataStoreLazyLoadPostCommentWithCompositeKeyTests { typealias Post = PostWithCompositeKey typealias Comment = CommentWithCompositeKey - + struct PostCommentWithCompositeKeyModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift index 9b70a40965..d5835f7876 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension CommentWithCompositeKey { +public extension CommentWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let commentWithCompositeKey = CommentWithCompositeKey.keys - + model.pluralName = "CommentWithCompositeKeys" - + model.attributes( .index(fields: ["id", "content"], name: nil), .primaryKey(fields: [commentWithCompositeKey.id, commentWithCompositeKey.content]) ) - + model.fields( .field(commentWithCompositeKey.id, is: .required, ofType: .string), .field(commentWithCompositeKey.content, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension CommentWithCompositeKey { .field(commentWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension CommentWithCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension CommentWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension CommentWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - content: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "content", value: content)]) +public extension CommentWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + content: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "content", value: content)]) } } -extension ModelPath where ModelType == CommentWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == CommentWithCompositeKey { + var id: FieldPath { string("id") } - public var content: FieldPath { + var content: FieldPath { string("content") } - public var post: ModelPath { + var post: ModelPath { PostWithCompositeKey.Path(name: "post", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey.swift index c3db0086aa..7e483fc203 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/CommentWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct CommentWithCompositeKey: Model { public let id: String public let content: String - internal var _post: LazyReference + var _post: LazyReference public var post: PostWithCompositeKey? { get async throws { try await _post.get() @@ -13,21 +20,27 @@ public struct CommentWithCompositeKey: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil) { - self.init(id: id, - content: content, - post: post, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil + ) { + self.init( + id: id, + content: content, + post: post, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: PostWithCompositeKey? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: PostWithCompositeKey? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self._post = LazyReference(post) @@ -35,15 +48,15 @@ public struct CommentWithCompositeKey: Model { self.updatedAt = updatedAt } public mutating func setPost(_ post: PostWithCompositeKey? = nil) { - self._post = LazyReference(post) + _post = LazyReference(post) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - content = try values.decode(String.self, forKey: .content) - _post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self.content = try values.decode(String.self, forKey: .content) + self._post = try values.decodeIfPresent(LazyReference.self, forKey: .post) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift index 04c89f21f1..a7061afc79 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithCompositeKey { +public extension PostWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let postWithCompositeKey = PostWithCompositeKey.keys - + model.pluralName = "PostWithCompositeKeys" - + model.attributes( .index(fields: ["id", "title"], name: nil), .primaryKey(fields: [postWithCompositeKey.id, postWithCompositeKey.title]) ) - + model.fields( .field(postWithCompositeKey.id, is: .required, ofType: .string), .field(postWithCompositeKey.title, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension PostWithCompositeKey { .field(postWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PostWithCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension PostWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - title: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "title", value: title)]) +public extension PostWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + title: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "title", value: title)]) } } -extension ModelPath where ModelType == PostWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == PostWithCompositeKey { + var id: FieldPath { string("id") } - public var title: FieldPath { + var title: FieldPath { string("title") } - public var comments: ModelPath { + var comments: ModelPath { CommentWithCompositeKey.Path(name: "comments", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey.swift index e9de7de986..ac441cae5d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL3/PostWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithCompositeKey: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagSnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagSnapshotTests.swift index fa0b254a08..a0af212826 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagSnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagSnapshotTests.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostTagTests { - + func testPostSelectionSets() async throws { await setup(withModels: PostTagModels()) continueAfterFailure = true - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -40,11 +40,11 @@ extension AWSDataStoreLazyLoadPostTagTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testTagSelectionSets() async throws { await setup(withModels: PostTagModels()) continueAfterFailure = true - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Tag.self) let syncDocument = """ @@ -67,11 +67,11 @@ extension AWSDataStoreLazyLoadPostTagTests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testPostTagSelectionSets() async throws { await setup(withModels: PostTagModels()) continueAfterFailure = true - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: PostTag.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagTests.swift index b750c45194..16ba9ce97c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/AWSDataStoreLazyLoadPostTagTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { @@ -18,7 +18,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { await setup(withModels: PostTagModels()) try await startAndWaitForReady() } - + func testLazyLoad() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -27,7 +27,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) let savedPostTag = try await createAndWaitForSync(postTag) - + try await assertPost(savedPost, canLazyLoad: savedPostTag) try await assertTag(savedTag, canLazyLoad: savedPostTag) assertLazyReference( @@ -51,44 +51,54 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let queriedPostTag = try await query(for: savedPostTag) try await assertPostTag(queriedPostTag, canLazyLoadTag: savedTag, canLazyLoadPost: savedPost) } - - func assertPost(_ post: Post, - canLazyLoad postTag: PostTag) async throws { + + func assertPost( + _ post: Post, + canLazyLoad postTag: PostTag + ) async throws { guard let postTags = post.tags else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIds: [post.identifier], - associatedFields: ["postWithTagsCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIds: [post.identifier], + associatedFields: ["postWithTagsCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 1)) } - - func assertTag(_ tag: Tag, - canLazyLoad postTag: PostTag) async throws { + + func assertTag( + _ tag: Tag, + canLazyLoad postTag: PostTag + ) async throws { guard let postTags = tag.posts else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIds: [tag.identifier], - associatedFields: ["tagWithCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIds: [tag.identifier], + associatedFields: ["tagWithCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 1)) } - + func assertPostTag(_ postTag: PostTag, canLazyLoadTag tag: Tag, canLazyLoadPost post: Post) async throws { assertLazyReference( postTag._tagWithCompositeKey, state: .notLoaded(identifiers: [ .init(name: Tag.keys.id.stringValue, value: tag.id), .init(name: Tag.keys.name.stringValue, value: tag.name) - ])) + ]) + ) assertLazyReference( postTag._postWithTagsCompositeKey, state: .notLoaded(identifiers: [ .init(name: Post.keys.postId.stringValue, value: post.postId), .init(name: Post.keys.title.stringValue, value: post.title) - ])) + ]) + ) let loadedTag = try await postTag.tagWithCompositeKey assertLazyReference(postTag._tagWithCompositeKey, state: .loaded(model: loadedTag)) try await assertTag(loadedTag, canLazyLoad: postTag) @@ -96,7 +106,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { assertLazyReference(postTag._postWithTagsCompositeKey, state: .loaded(model: loadedPost)) try await assertPost(loadedPost, canLazyLoad: postTag) } - + func testUpdate() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -105,7 +115,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) let savedPostTag = try await createAndWaitForSync(postTag) - + // update the post tag with a new post var queriedPostTag = try await query(for: savedPostTag) let newPost = Post(postId: UUID().uuidString, title: "title") @@ -121,7 +131,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { ) let queriedPreviousPost = try await query(for: savedPost) try await assertPostWithNoPostTag(queriedPreviousPost) - + // update the post tag with a new tag var queriedPostTagWithNewPost = try await query(for: savedPostTagWithNewPost) let newTag = Tag(name: "name") @@ -138,29 +148,33 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let queriedPreviousTag = try await query(for: savedTag) try await assertTagWithNoPostTag(queriedPreviousTag) } - + func assertPostWithNoPostTag(_ post: Post) async throws { guard let postTags = post.tags else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIds: [post.identifier], - associatedFields: ["postWithTagsCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIds: [post.identifier], + associatedFields: ["postWithTagsCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 0)) } - + func assertTagWithNoPostTag(_ tag: Tag) async throws { guard let postTags = tag.posts else { XCTFail("Missing postTags on post") return } - assertList(postTags, state: .isNotLoaded(associatedIds: [tag.identifier], - associatedFields: ["tagWithCompositeKey"])) + assertList(postTags, state: .isNotLoaded( + associatedIds: [tag.identifier], + associatedFields: ["tagWithCompositeKey"] + )) try await postTags.fetch() assertList(postTags, state: .isLoaded(count: 0)) } - + func testDeletePost() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -169,14 +183,14 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) let savedPostTag = try await createAndWaitForSync(postTag) - + try await deleteAndWaitForSync(savedPost) - + try await assertModelDoesNotExist(savedPost) try await assertModelExists(savedTag) try await assertModelDoesNotExist(savedPostTag) } - + func testDeleteTag() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -185,14 +199,14 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) let savedPostTag = try await createAndWaitForSync(postTag) - + try await deleteAndWaitForSync(savedTag) - + try await assertModelExists(savedPost) try await assertModelDoesNotExist(savedTag) try await assertModelDoesNotExist(savedPostTag) } - + func testDeletePostTag() async throws { await setup(withModels: PostTagModels()) let post = Post(postId: UUID().uuidString, title: "title") @@ -201,14 +215,14 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) let savedPostTag = try await createAndWaitForSync(postTag) - + try await deleteAndWaitForSync(savedPostTag) - + try await assertModelExists(savedPost) try await assertModelExists(savedTag) try await assertModelDoesNotExist(savedPostTag) } - + func testObservePost() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() @@ -221,7 +235,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedPost = try? mutationEvent.decodeModel(as: Post.self), receivedPost.postId == post.postId { - + guard let tags = receivedPost.tags else { XCTFail("Lazy List does not exist") return @@ -232,7 +246,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load \(error)") } XCTAssertEqual(tags.count, 0) - + mutationEventReceived.fulfill() } } @@ -243,16 +257,16 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveTag() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() let tag = Tag(name: "name") - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Tag.self) Task { @@ -271,7 +285,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load \(error)") } XCTAssertEqual(posts.count, 0) - + mutationEventReceived.fulfill() } } @@ -282,11 +296,11 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObservePostTag() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() @@ -294,10 +308,11 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let tag = Tag(name: "name") let savedPost = try await createAndWaitForSync(post) let savedTag = try await createAndWaitForSync(tag) - _ = savedPost; _ = savedTag + _ = savedPost + _ = savedTag let postTag = PostTag(postWithTagsCompositeKey: post, tagWithCompositeKey: tag) - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(PostTag.self) Task { @@ -306,24 +321,24 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedPostTag = try? mutationEvent.decodeModel(as: PostTag.self), receivedPostTag.id == postTag.id { - + try await assertPostTag(receivedPostTag, canLazyLoadTag: tag, canLazyLoadPost: post) mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: postTag, modelSchema: PostTag.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() @@ -343,7 +358,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load \(error)") } XCTAssertEqual(tags.count, 0) - + snapshotReceived.fulfill() } } @@ -354,16 +369,16 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryTag() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() let tag = Tag(name: "name") - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Tag.self, where: Tag.keys.id == tag.id) Task { @@ -379,7 +394,7 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { XCTFail("Failed to lazy load \(error)") } XCTAssertEqual(posts.count, 0) - + snapshotReceived.fulfill() } } @@ -390,11 +405,11 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryPostTag() async throws { await setup(withModels: PostTagModels()) try await startAndWaitForReady() @@ -402,9 +417,9 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { let tag = Tag(name: "name") try await createAndWaitForSync(post) try await createAndWaitForSync(tag) - + let postTag = PostTag(postWithTagsCompositeKey: post, tagWithCompositeKey: tag) - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: PostTag.self, where: PostTag.keys.id == postTag.id) Task { @@ -415,14 +430,14 @@ final class AWSDataStoreLazyLoadPostTagTests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: postTag, modelSchema: PostTag.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -432,7 +447,7 @@ extension AWSDataStoreLazyLoadPostTagTests { typealias Post = PostWithTagsCompositeKey typealias Tag = TagWithCompositeKey typealias PostTag = PostTagsWithCompositeKey - + struct PostTagModels: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift index 59cd80dd74..9ea2ee8d95 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey+Schema.swift @@ -1,31 +1,38 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostTagsWithCompositeKey { +public extension PostTagsWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case postWithTagsCompositeKey case tagWithCompositeKey case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let postTagsWithCompositeKey = PostTagsWithCompositeKey.keys - + model.pluralName = "PostTagsWithCompositeKeys" - + model.attributes( .index(fields: ["postWithTagsCompositeKeyPostId", "postWithTagsCompositeKeytitle"], name: "byPostWithTagsCompositeKey"), .index(fields: ["tagWithCompositeKeyId", "tagWithCompositeKeyname"], name: "byTagWithCompositeKey"), .primaryKey(fields: [postTagsWithCompositeKey.id]) ) - + model.fields( .field(postTagsWithCompositeKey.id, is: .required, ofType: .string), .belongsTo(postTagsWithCompositeKey.postWithTagsCompositeKey, is: .required, ofType: PostWithTagsCompositeKey.self, targetNames: ["postWithTagsCompositeKeyPostId", "postWithTagsCompositeKeytitle"]), @@ -34,29 +41,29 @@ extension PostTagsWithCompositeKey { .field(postTagsWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PostTagsWithCompositeKey: ModelIdentifiable { public typealias IdentifierFormat = ModelIdentifierFormat.Default public typealias IdentifierProtocol = DefaultModelIdentifier } -extension ModelPath where ModelType == PostTagsWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == PostTagsWithCompositeKey { + var id: FieldPath { string("id") } - public var postWithTagsCompositeKey: ModelPath { + var postWithTagsCompositeKey: ModelPath { PostWithTagsCompositeKey.Path(name: "postWithTagsCompositeKey", parent: self) } - public var tagWithCompositeKey: ModelPath { + var tagWithCompositeKey: ModelPath { TagWithCompositeKey.Path(name: "tagWithCompositeKey", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift index a248ebe072..45108cf5a8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostTagsWithCompositeKey.swift @@ -1,16 +1,23 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation public struct PostTagsWithCompositeKey: Model { public let id: String - internal var _postWithTagsCompositeKey: LazyReference + var _postWithTagsCompositeKey: LazyReference public var postWithTagsCompositeKey: PostWithTagsCompositeKey { get async throws { try await _postWithTagsCompositeKey.require() } } - internal var _tagWithCompositeKey: LazyReference + var _tagWithCompositeKey: LazyReference public var tagWithCompositeKey: TagWithCompositeKey { get async throws { try await _tagWithCompositeKey.require() @@ -18,21 +25,27 @@ public struct PostTagsWithCompositeKey: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - postWithTagsCompositeKey: PostWithTagsCompositeKey, - tagWithCompositeKey: TagWithCompositeKey) { - self.init(id: id, - postWithTagsCompositeKey: postWithTagsCompositeKey, - tagWithCompositeKey: tagWithCompositeKey, - createdAt: nil, - updatedAt: nil) + + public init( + id: String = UUID().uuidString, + postWithTagsCompositeKey: PostWithTagsCompositeKey, + tagWithCompositeKey: TagWithCompositeKey + ) { + self.init( + id: id, + postWithTagsCompositeKey: postWithTagsCompositeKey, + tagWithCompositeKey: tagWithCompositeKey, + createdAt: nil, + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - postWithTagsCompositeKey: PostWithTagsCompositeKey, - tagWithCompositeKey: TagWithCompositeKey, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + postWithTagsCompositeKey: PostWithTagsCompositeKey, + tagWithCompositeKey: TagWithCompositeKey, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self._postWithTagsCompositeKey = LazyReference(postWithTagsCompositeKey) self._tagWithCompositeKey = LazyReference(tagWithCompositeKey) @@ -40,18 +53,18 @@ public struct PostTagsWithCompositeKey: Model { self.updatedAt = updatedAt } public mutating func setPostWithTagsCompositeKey(_ postWithTagsCompositeKey: PostWithTagsCompositeKey) { - self._postWithTagsCompositeKey = LazyReference(postWithTagsCompositeKey) + _postWithTagsCompositeKey = LazyReference(postWithTagsCompositeKey) } public mutating func setTagWithCompositeKey(_ tagWithCompositeKey: TagWithCompositeKey) { - self._tagWithCompositeKey = LazyReference(tagWithCompositeKey) + _tagWithCompositeKey = LazyReference(tagWithCompositeKey) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - id = try values.decode(String.self, forKey: .id) - _postWithTagsCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .postWithTagsCompositeKey) ?? LazyReference(identifiers: nil) - _tagWithCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .tagWithCompositeKey) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.id = try values.decode(String.self, forKey: .id) + self._postWithTagsCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .postWithTagsCompositeKey) ?? LazyReference(identifiers: nil) + self._tagWithCompositeKey = try values.decodeIfPresent(LazyReference.self, forKey: .tagWithCompositeKey) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift index 888c9b969a..eeb2570973 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension PostWithTagsCompositeKey { +public extension PostWithTagsCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case postId case title case tags case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let postWithTagsCompositeKey = PostWithTagsCompositeKey.keys - + model.pluralName = "PostWithTagsCompositeKeys" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [postWithTagsCompositeKey.postId, postWithTagsCompositeKey.title]) ) - + model.fields( .field(postWithTagsCompositeKey.postId, is: .required, ofType: .string), .field(postWithTagsCompositeKey.title, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension PostWithTagsCompositeKey { .field(postWithTagsCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension PostWithTagsCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension PostWithTagsCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension PostWithTagsCompositeKey.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension PostWithTagsCompositeKey.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } -extension ModelPath where ModelType == PostWithTagsCompositeKey { - public var postId: FieldPath { +public extension ModelPath where ModelType == PostWithTagsCompositeKey { + var postId: FieldPath { string("postId") } - public var title: FieldPath { + var title: FieldPath { string("title") } - public var tags: ModelPath { + var tags: ModelPath { PostTagsWithCompositeKey.Path(name: "tags", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift index c739bc9c22..73e3e3cd7c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/PostWithTagsCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct PostWithTagsCompositeKey: Model { public var tags: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - tags: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + tags: List? = [] + ) { + self.init( + postId: postId, title: title, tags: tags, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - tags: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + tags: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.tags = tags self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift index 95a6c9bf82..c6dc88f2f2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension TagWithCompositeKey { +public extension TagWithCompositeKey { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let tagWithCompositeKey = TagWithCompositeKey.keys - + model.pluralName = "TagWithCompositeKeys" - + model.attributes( .index(fields: ["id", "name"], name: nil), .primaryKey(fields: [tagWithCompositeKey.id, tagWithCompositeKey.name]) ) - + model.fields( .field(tagWithCompositeKey.id, is: .required, ofType: .string), .field(tagWithCompositeKey.name, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension TagWithCompositeKey { .field(tagWithCompositeKey.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension TagWithCompositeKey: ModelIdentifiable { @@ -43,26 +50,28 @@ extension TagWithCompositeKey: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension TagWithCompositeKey.IdentifierProtocol { - public static func identifier(id: String, - name: String) -> Self { - .make(fields:[(name: "id", value: id), (name: "name", value: name)]) +public extension TagWithCompositeKey.IdentifierProtocol { + static func identifier( + id: String, + name: String + ) -> Self { + .make(fields: [(name: "id", value: id), (name: "name", value: name)]) } } -extension ModelPath where ModelType == TagWithCompositeKey { - public var id: FieldPath { +public extension ModelPath where ModelType == TagWithCompositeKey { + var id: FieldPath { string("id") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var posts: ModelPath { + var posts: ModelPath { PostTagsWithCompositeKey.Path(name: "posts", isCollection: true, parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey.swift index 8d8bbf9f26..b913c944db 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL4/TagWithCompositeKey.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct TagWithCompositeKey: Model { public var posts: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1SnapshotTests.swift index 426971f78f..1c75c040a8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1SnapshotTests.swift @@ -5,20 +5,22 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @testable import AWSPluginsCore extension AWSDataStoreLazyLoadProjectTeam1Tests { - + func testProjectSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam1Models()) continueAfterFailure = true - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) // Create let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) let createDocument = """ @@ -48,7 +50,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: project, modelSchema: Project.schema) let updateDocument = """ @@ -78,7 +80,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: project, modelSchema: Project.schema) let deleteDocument = """ @@ -108,7 +110,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -134,7 +136,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -160,7 +162,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -186,7 +188,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Project.self) let syncDocument = """ @@ -217,12 +219,12 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testTeamSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam1Models()) continueAfterFailure = true let team = Team(teamId: UUID().uuidString, name: "name") - + // Create let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) let createDocument = """ @@ -252,7 +254,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: team, modelSchema: Team.schema) let updateDocument = """ @@ -282,7 +284,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: team, modelSchema: Team.schema) let deleteDocument = """ @@ -312,7 +314,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Team.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -336,7 +338,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -360,7 +362,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -384,7 +386,7 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Team.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1Tests.swift index 0d0929e5f5..cad591c842 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/AWSDataStoreLazyLoadProjectTeam1Tests.swift @@ -5,80 +5,88 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @testable import AWSPluginsCore class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: ProjectTeam1Models()) try await startAndWaitForReady() printDBPath() } - + func testSaveTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam1Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await createAndWaitForSync(project) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - project1TeamTeamId: team.teamId, - project1TeamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project1TeamTeamId: team.teamId, + project1TeamName: team.name + ) let savedProject = try await createAndWaitForSync(project) let queriedProject = try await query(for: savedProject) assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await createAndWaitForSync(project2) let queriedProject2 = try await query(for: savedProject2) assertProjectDoesNotContainTeam(queriedProject2) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - project1TeamTeamId: team.teamId, - project1TeamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + project1TeamTeamId: team.teamId, + project1TeamName: team.name + ) let savedProject3 = try await createAndWaitForSync(project3) let queriedProject3 = try await query(for: savedProject3) assertProject(queriedProject3, hasTeam: savedTeam) } - + func testSaveProjectWithTeamThenAccessProjectFromTeam() async throws { await setup(withModels: ProjectTeam1Models()) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let projectWithTeam = initializeProjectWithTeam(savedTeam) let savedProjectWithTeam = try await createAndWaitForSync(projectWithTeam) let queriedProjectWithTeam = try await query(for: savedProjectWithTeam) assertProject(queriedProjectWithTeam, hasTeam: savedTeam) - + // For bi-directional has-one belongs-to, we require setting the FK on both sides // Thus, when querying for the team `queriedTeam`, the team does not have the project. var queriedTeam = try await query(for: savedTeam) @@ -87,7 +95,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { // Update the team with the project. queriedTeam.setProject(queriedProjectWithTeam) let savedTeamWithProject = try await updateAndWaitForSync(queriedTeam) - + assertLazyReference( savedTeamWithProject._project, state: .notLoaded(identifiers: [ @@ -100,11 +108,11 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { .init(name: Project.keys.projectId.stringValue, value: projectWithTeam.projectId), .init(name: Project.keys.name.stringValue, value: projectWithTeam.name) ])) - + let loadedProject = try await queriedTeamWithProject.project! XCTAssertEqual(loadedProject.projectId, projectWithTeam.projectId) } - + // One-to-One relationships do not create a foreign key for the Team or Project table // So the LazyModel does not have the FK value to be instantiated as metadata for lazy loading. // We only assert the FK fields on the Project exist and are equal to the Team's PK. @@ -112,12 +120,12 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { XCTAssertEqual(project.project1TeamTeamId, team.teamId) XCTAssertEqual(project.project1TeamName, team.name) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.project1TeamTeamId) XCTAssertNil(project.project1TeamName) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -130,13 +138,13 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { let updatedProject = try await updateAndWaitForSync(project) assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam1Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await createAndWaitForSync(project) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) var queriedProject = try await query(for: savedProject) @@ -145,7 +153,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -159,7 +167,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNoTeam = try await updateAndWaitForSync(queriedProject) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -175,7 +183,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(queriedProject, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -184,7 +192,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam1Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -193,33 +201,33 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedProject) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam1Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedProject) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testObserveProject() async throws { await setup(withModels: ProjectTeam1Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Project.self) Task { @@ -233,18 +241,18 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveTeam() async throws { await setup(withModels: ProjectTeam1Models()) try await startAndWaitForReady() @@ -257,30 +265,30 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedTeam = try? mutationEvent.decodeModel(as: Team.self), receivedTeam.teamId == team.teamId { - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryProject() async throws { await setup(withModels: ProjectTeam1Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Project.self, where: Project.keys.projectId == project.projectId) Task { @@ -291,18 +299,18 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryTeam() async throws { await setup(withModels: ProjectTeam1Models()) try await startAndWaitForReady() @@ -317,14 +325,14 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -333,7 +341,7 @@ class AWSDataStoreLazyLoadProjectTeam1Tests: AWSDataStoreLazyLoadBaseTest { extension AWSDataStoreLazyLoadProjectTeam1Tests { typealias Project = Project1 typealias Team = Team1 - + struct ProjectTeam1Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -341,12 +349,14 @@ extension AWSDataStoreLazyLoadProjectTeam1Tests { ModelRegistry.register(modelType: Team1.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - project1TeamTeamId: team.teamId, - project1TeamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project1TeamTeamId: team.teamId, + project1TeamName: team.name + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1+Schema.swift index cb052507f7..68ffadac0f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project1 { +public extension Project1 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project1 { case project1TeamTeamId case project1TeamName } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let project1 = Project1.keys - + model.pluralName = "Project1s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project1.projectId, project1.name]) ) - + model.fields( .field(project1.projectId, is: .required, ofType: .string), .field(project1.name, is: .required, ofType: .string), @@ -37,9 +44,9 @@ extension Project1 { .field(project1.project1TeamName, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project1: ModelIdentifiable { @@ -47,32 +54,34 @@ extension Project1: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project1.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project1.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } -extension ModelPath where ModelType == Project1 { - public var projectId: FieldPath { +public extension ModelPath where ModelType == Project1 { + var projectId: FieldPath { string("projectId") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var team: ModelPath { + var team: ModelPath { Team1.Path(name: "team", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } - public var project1TeamTeamId: FieldPath { + var project1TeamTeamId: FieldPath { string("project1TeamTeamId") } - public var project1TeamName: FieldPath { + var project1TeamName: FieldPath { string("project1TeamName") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1.swift index a36917b1ba..550860a378 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Project1.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project1: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team1? { get async throws { try await _team.get() @@ -15,27 +22,33 @@ public struct Project1: Model { public var updatedAt: Temporal.DateTime? public var project1TeamTeamId: String? public var project1TeamName: String? - - public init(projectId: String, - name: String, - team: Team1? = nil, - project1TeamTeamId: String? = nil, - project1TeamName: String? = nil) { - self.init(projectId: projectId, - name: name, - team: team, - createdAt: nil, - updatedAt: nil, - project1TeamTeamId: project1TeamTeamId, - project1TeamName: project1TeamName) + + public init( + projectId: String, + name: String, + team: Team1? = nil, + project1TeamTeamId: String? = nil, + project1TeamName: String? = nil + ) { + self.init( + projectId: projectId, + name: name, + team: team, + createdAt: nil, + updatedAt: nil, + project1TeamTeamId: project1TeamTeamId, + project1TeamName: project1TeamName + ) } - internal init(projectId: String, - name: String, - team: Team1? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project1TeamTeamId: String? = nil, - project1TeamName: String? = nil) { + init( + projectId: String, + name: String, + team: Team1? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project1TeamTeamId: String? = nil, + project1TeamName: String? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -45,17 +58,17 @@ public struct Project1: Model { self.project1TeamName = project1TeamName } public mutating func setTeam(_ team: Team1? = nil) { - self._team = LazyReference(team) + _team = LazyReference(team) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - project1TeamTeamId = try? values.decode(String?.self, forKey: .project1TeamTeamId) - project1TeamName = try? values.decode(String?.self, forKey: .project1TeamName) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.project1TeamTeamId = try? values.decode(String?.self, forKey: .project1TeamTeamId) + self.project1TeamName = try? values.decode(String?.self, forKey: .project1TeamName) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1+Schema.swift index 1ac9b09f53..c29406367b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team1 { +public extension Team1 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case teamId case name case project case createdAt case updatedAt } - - public static let keys = CodingKeys.self + + static let keys = CodingKeys.self // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let schema = defineSchema { model in let team1 = Team1.keys - + model.pluralName = "Team1s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team1.teamId, team1.name]) ) - + model.fields( .field(team1.teamId, is: .required, ofType: .string), .field(team1.name, is: .required, ofType: .string), @@ -33,9 +40,9 @@ extension Team1 { .field(team1.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team1: ModelIdentifiable { @@ -43,26 +50,28 @@ extension Team1: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team1.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team1.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } -extension ModelPath where ModelType == Team1 { - public var teamId: FieldPath { +public extension ModelPath where ModelType == Team1 { + var teamId: FieldPath { string("teamId") } - public var name: FieldPath { + var name: FieldPath { string("name") } - public var project: ModelPath { + var project: ModelPath { Project1.Path(name: "project", parent: self) } - public var createdAt: FieldPath { + var createdAt: FieldPath { datetime("createdAt") } - public var updatedAt: FieldPath { + var updatedAt: FieldPath { datetime("updatedAt") } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1.swift index c29c0e2252..8483e5515c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL5/Team1.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Team1: Model { public let teamId: String public let name: String - internal var _project: LazyReference + var _project: LazyReference public var project: Project1? { get async throws { try await _project.get() @@ -13,21 +20,27 @@ public struct Team1: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String, - project: Project1? = nil) { - self.init(teamId: teamId, - name: name, - project: project, - createdAt: nil, - updatedAt: nil) + + public init( + teamId: String, + name: String, + project: Project1? = nil + ) { + self.init( + teamId: teamId, + name: name, + project: project, + createdAt: nil, + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - project: Project1? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + project: Project1? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self._project = LazyReference(project) @@ -35,15 +48,15 @@ public struct Team1: Model { self.updatedAt = updatedAt } public mutating func setProject(_ project: Project1? = nil) { - self._project = LazyReference(project) + _project = LazyReference(project) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - teamId = try values.decode(String.self, forKey: .teamId) - name = try values.decode(String.self, forKey: .name) - _project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) - createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.teamId = try values.decode(String.self, forKey: .teamId) + self.name = try values.decode(String.self, forKey: .name) + self._project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) + self.createdAt = try? values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try? values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2SnapshotTests.swift index bd8e430e0d..8cc1c1d9c3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2SnapshotTests.swift @@ -5,20 +5,22 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadProjectTeam2Tests { - + func testProjectSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam2Models()) continueAfterFailure = true - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) // Create let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) let createDocument = """ @@ -48,7 +50,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: project, modelSchema: Project.schema) let updateDocument = """ @@ -78,7 +80,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: project, modelSchema: Project.schema) let deleteDocument = """ @@ -108,7 +110,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -134,7 +136,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -160,7 +162,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -186,7 +188,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Project.self) let syncDocument = """ @@ -217,12 +219,12 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testTeamSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam2Models()) continueAfterFailure = true let team = Team(teamId: UUID().uuidString, name: "name") - + // Create let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) let createDocument = """ @@ -240,7 +242,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: team, modelSchema: Team.schema) let updateDocument = """ @@ -258,7 +260,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: team, modelSchema: Team.schema) let deleteDocument = """ @@ -276,7 +278,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Team.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -294,7 +296,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -312,7 +314,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -330,7 +332,7 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Team.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2Tests.swift index 8a2344a0fd..d8e93f132c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/AWSDataStoreLazyLoadProjectTeam2Tests.swift @@ -5,70 +5,78 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: ProjectTeam2Models()) try await startAndWaitForReady() printDBPath() } - + func testSaveTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam2Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await createAndWaitForSync(project) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - project2TeamTeamId: team.teamId, - project2TeamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project2TeamTeamId: team.teamId, + project2TeamName: team.name + ) let savedProject = try await createAndWaitForSync(project) let queriedProject = try await query(for: savedProject) assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await createAndWaitForSync(project2) let queriedProject2 = try await query(for: savedProject2) assertProjectDoesNotContainTeam(queriedProject2) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - project2TeamTeamId: team.teamId, - project2TeamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + project2TeamTeamId: team.teamId, + project2TeamName: team.name + ) let savedProject3 = try await createAndWaitForSync(project3) let queriedProject3 = try await query(for: savedProject3) assertProject(queriedProject3, hasTeam: savedTeam) } - + // One-to-One relationships do not create a foreign key for the Team or Project table // So the LazyModel does not have the FK value to be instantiated as metadata for lazy loading. // We only assert the FK fields on the Project exist and are equal to the Team's PK. @@ -76,17 +84,17 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { XCTAssertEqual(project.project2TeamTeamId, team.teamId) XCTAssertEqual(project.project2TeamName, team.name) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.project2TeamTeamId) XCTAssertNil(project.project2TeamName) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) assertProject(savedProject, hasTeam: savedTeam) @@ -95,13 +103,13 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { let updatedProject = try await updateAndWaitForSync(project) assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam2Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await createAndWaitForSync(project) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) var queriedProject = try await query(for: savedProject) @@ -110,7 +118,7 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -124,7 +132,7 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNoTeam = try await updateAndWaitForSync(queriedProject) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -142,7 +150,7 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { let queriedProjectV2 = try await query(for: savedProject) assertProject(queriedProjectV2, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -151,7 +159,7 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam2Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -160,33 +168,33 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedProject) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam2Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedProject) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testObserveProject() async throws { await setup(withModels: ProjectTeam2Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Project.self) Task { @@ -200,18 +208,18 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveTeam() async throws { await setup(withModels: ProjectTeam2Models()) try await startAndWaitForReady() @@ -224,30 +232,30 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedTeam = try? mutationEvent.decodeModel(as: Team.self), receivedTeam.teamId == team.teamId { - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryProject() async throws { await setup(withModels: ProjectTeam2Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Project.self, where: Project.keys.projectId == project.projectId) Task { @@ -258,18 +266,18 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryTeam() async throws { await setup(withModels: ProjectTeam2Models()) try await startAndWaitForReady() @@ -284,24 +292,24 @@ class AWSDataStoreLazyLoadProjectTeam2Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } } extension AWSDataStoreLazyLoadProjectTeam2Tests { - + typealias Project = Project2 typealias Team = Team2 - + struct ProjectTeam2Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -309,12 +317,14 @@ extension AWSDataStoreLazyLoadProjectTeam2Tests { ModelRegistry.register(modelType: Team2.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - project2TeamTeamId: team.teamId, - project2TeamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + project2TeamTeamId: team.teamId, + project2TeamName: team.name + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2+Schema.swift index 79361d58a5..4d90db0806 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project2 { +public extension Project2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -14,10 +21,10 @@ extension Project2 { case project2TeamName } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project2 = Project2.keys model.pluralName = "Project2s" @@ -37,10 +44,10 @@ extension Project2 { .field(project2.project2TeamName, is: .optional, ofType: .string) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project2: ModelIdentifiable { @@ -48,10 +55,12 @@ extension Project2: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project2.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project2.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2.swift index 2e05879e89..d35250d7ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Project2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project2: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team2? { get async throws { try await _team.get() @@ -16,26 +23,32 @@ public struct Project2: Model { public var project2TeamTeamId: String? public var project2TeamName: String? - public init(projectId: String, - name: String, - team: Team2? = nil, - project2TeamTeamId: String? = nil, - project2TeamName: String? = nil) { - self.init(projectId: projectId, - name: name, - team: team, - createdAt: nil, - updatedAt: nil, - project2TeamTeamId: project2TeamTeamId, - project2TeamName: project2TeamName) + public init( + projectId: String, + name: String, + team: Team2? = nil, + project2TeamTeamId: String? = nil, + project2TeamName: String? = nil + ) { + self.init( + projectId: projectId, + name: name, + team: team, + createdAt: nil, + updatedAt: nil, + project2TeamTeamId: project2TeamTeamId, + project2TeamName: project2TeamName + ) } - internal init(projectId: String, - name: String, - team: Team2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project2TeamTeamId: String? = nil, - project2TeamName: String? = nil) { + init( + projectId: String, + name: String, + team: Team2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project2TeamTeamId: String? = nil, + project2TeamName: String? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -46,18 +59,18 @@ public struct Project2: Model { } public mutating func setTeam(_ team: Team2?) { - self._team = LazyReference(team) + _team = LazyReference(team) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) - project2TeamTeamId = try values.decode(String?.self, forKey: .project2TeamTeamId) - project2TeamName = try values.decode(String?.self, forKey: .project2TeamName) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.project2TeamTeamId = try values.decode(String?.self, forKey: .project2TeamTeamId) + self.project2TeamName = try values.decode(String?.self, forKey: .project2TeamName) } public func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2+Schema.swift index 58ae64d03a..bcb5656050 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team2 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team2 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case teamId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team2 = Team2.keys - + model.pluralName = "Team2s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team2.teamId, team2.name]) ) - + model.fields( .field(team2.teamId, is: .required, ofType: .string), .field(team2.name, is: .required, ofType: .string), @@ -31,10 +38,10 @@ extension Team2 { .field(team2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team2: ModelIdentifiable { @@ -42,10 +49,12 @@ extension Team2: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team2.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team2.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2.swift index 90d68caa79..f58e821d6e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL6/Team2.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Team2: Model { public let name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String) { - self.init(teamId: teamId, + + public init( + teamId: String, + name: String + ) { + self.init( + teamId: teamId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4SnapshotTests.swift index 35fbad0e66..0eca4c64ce 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4SnapshotTests.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadPostComment4Tests { - + func testPostSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment4Models()) continueAfterFailure = true @@ -35,7 +35,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: post, modelSchema: Post.schema) let updateDocument = """ @@ -53,7 +53,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: post, modelSchema: Post.schema) let deleteDocument = """ @@ -71,7 +71,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -89,7 +89,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -107,7 +107,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Post.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -125,7 +125,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Post.self) let syncDocument = """ @@ -148,16 +148,18 @@ extension AWSDataStoreLazyLoadPostComment4Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testCommentSelectionSets() { setUpModelRegistrationOnly(withModels: PostComment4Models()) continueAfterFailure = true let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) - + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) + // Create let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) let createDocument = """ @@ -177,7 +179,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: comment, modelSchema: Comment.schema) let updateDocument = """ @@ -197,7 +199,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: comment, modelSchema: Comment.schema) let deleteDocument = """ @@ -217,7 +219,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Comment.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -237,7 +239,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -257,7 +259,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Comment.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -277,7 +279,7 @@ extension AWSDataStoreLazyLoadPostComment4Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Comment.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4Tests.swift index 3a56f66da5..ec5123e7a7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/AWSDataStoreLazyLoadPostComment4Tests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest { @@ -19,31 +19,35 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) } - + func testSaveComment() async throws { await setup(withModels: PostComment4Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) } - + func testLazyLoad() async throws { await setup(withModels: PostComment4Models()) let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) assertComment(savedComment, contains: savedPost) try await assertPost(savedPost, canLazyLoad: savedComment) - + // Assert on Queried Comment let queriedComment = try await query(for: savedComment) assertComment(queriedComment, contains: savedPost) @@ -52,25 +56,29 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest let queriedPost = try await query(for: savedPost) try await assertPost(queriedPost, canLazyLoad: savedComment) } - + func assertComment(_ comment: Comment, contains post: Post) { XCTAssertEqual(comment.post4CommentsPostId, post.postId) XCTAssertEqual(comment.post4CommentsTitle, post.title) } - + func assertCommentDoesNotContainPost(_ comment: Comment) { XCTAssertNil(comment.post4CommentsPostId) XCTAssertNil(comment.post4CommentsTitle) } - - func assertPost(_ post: Post, - canLazyLoad comment: Comment) async throws { + + func assertPost( + _ post: Post, + canLazyLoad comment: Comment + ) async throws { guard let comments = post.comments else { XCTFail("Missing comments on post") return } - assertList(comments, state: .isNotLoaded(associatedIds: [post.postId, post.title], - associatedFields: ["post4CommentsPostId", "post4CommentsTitle"])) + assertList(comments, state: .isNotLoaded( + associatedIds: [post.postId, post.title], + associatedFields: ["post4CommentsPostId", "post4CommentsTitle"] + )) try await comments.fetch() assertList(comments, state: .isLoaded(count: 1)) guard let comment = comments.first else { @@ -79,7 +87,7 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest } assertComment(comment, contains: post) } - + func testSaveWithoutPost() async throws { await setup(withModels: PostComment4Models()) let comment = Comment(commentId: UUID().uuidString, content: "content") @@ -94,14 +102,16 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithPost) assertComment(queriedComment2, contains: post) } - + func testUpdateFromQueriedComment() async throws { await setup(withModels: PostComment4Models()) let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) let queriedComment = try await query(for: savedComment) @@ -110,15 +120,17 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: savedQueriedComment) assertComment(queriedComment2, contains: savedPost) } - + func testUpdateToNewPost() async throws { await setup(withModels: PostComment4Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) @@ -131,55 +143,61 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest let queriedComment2 = try await query(for: saveCommentWithNewPost) assertComment(queriedComment2, contains: newPost) } - + func testUpdateRemovePost() async throws { await setup(withModels: PostComment4Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) _ = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) var queriedComment = try await query(for: savedComment) assertComment(queriedComment, contains: post) - + queriedComment.post4CommentsPostId = nil queriedComment.post4CommentsTitle = nil - + let saveCommentRemovePost = try await updateAndWaitForSync(queriedComment) let queriedCommentNoPost = try await query(for: saveCommentRemovePost) assertCommentDoesNotContainPost(queriedCommentNoPost) } - + func testDelete() async throws { await setup(withModels: PostComment4Models()) - + let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let savedPost = try await createAndWaitForSync(post) let savedComment = try await createAndWaitForSync(comment) try await deleteAndWaitForSync(savedPost) - + // The expected behavior when deleting a post should be that the // child models are deleted (comment) followed by the parent model (post). try await assertModelDoesNotExist(savedPost) // Is there a way to delete the children models in uni directional relationships? try await assertModelExists(savedComment) } - + func testObservePost() async throws { await setup(withModels: PostComment4Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Post.self) Task { @@ -194,27 +212,29 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveComment() async throws { await setup(withModels: PostComment4Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Comment.self) Task { @@ -228,26 +248,28 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryPost() async throws { await setup(withModels: PostComment4Models()) try await startAndWaitForReady() let post = Post(postId: UUID().uuidString, title: "title") - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Post.self, where: Post.keys.postId == post.postId) Task { @@ -259,28 +281,30 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: post, modelSchema: Post.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryComment() async throws { await setup(withModels: PostComment4Models()) try await startAndWaitForReady() - + let post = Post(postId: UUID().uuidString, title: "title") let savedPost = try await createAndWaitForSync(post) - let comment = Comment(commentId: UUID().uuidString, - content: "content", - post4CommentsPostId: post.postId, - post4CommentsTitle: post.title) + let comment = Comment( + commentId: UUID().uuidString, + content: "content", + post4CommentsPostId: post.postId, + post4CommentsTitle: post.title + ) let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Comment.self, where: Comment.keys.commentId == comment.commentId) Task { @@ -291,14 +315,14 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest } } } - + let createRequest = GraphQLRequest.createMutation(of: comment, modelSchema: Comment.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } @@ -307,7 +331,7 @@ final class AWSDataStoreLazyLoadPostComment4Tests: AWSDataStoreLazyLoadBaseTest extension AWSDataStoreLazyLoadPostComment4Tests { typealias Post = Post4 typealias Comment = Comment4 - + struct PostComment4Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4+Schema.swift index fb694e6cf4..358ed06707 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Comment4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Comment4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case commentId case content case createdAt @@ -12,20 +19,20 @@ extension Comment4 { case post4CommentsPostId case post4CommentsTitle } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let comment4 = Comment4.keys - + model.pluralName = "Comment4s" - + model.attributes( .index(fields: ["commentId", "content"], name: nil), .primaryKey(fields: [comment4.commentId, comment4.content]) ) - + model.fields( .field(comment4.commentId, is: .required, ofType: .string), .field(comment4.content, is: .required, ofType: .string), @@ -35,9 +42,9 @@ extension Comment4 { .field(comment4.post4CommentsTitle, is: .optional, ofType: .string) ) } - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Comment4: ModelIdentifiable { @@ -45,10 +52,12 @@ extension Comment4: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Comment4.IdentifierProtocol { - public static func identifier(commentId: String, - content: String) -> Self { - .make(fields:[(name: "commentId", value: commentId), (name: "content", value: content)]) +public extension Comment4.IdentifierProtocol { + static func identifier( + commentId: String, + content: String + ) -> Self { + .make(fields: [(name: "commentId", value: commentId), (name: "content", value: content)]) } } @@ -59,5 +68,5 @@ extension ModelPath where ModelType == Comment4 { var updatedAt: FieldPath { datetime("updatedAt") } var post4CommentsPostId: FieldPath { string("post4CommentsPostId") } var post4CommentsTitle: FieldPath { string("post4CommentsTitle") } - + } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4.swift index bf249d1211..593b1efc60 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Comment4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -9,24 +16,30 @@ public struct Comment4: Model { public var updatedAt: Temporal.DateTime? public var post4CommentsPostId: String? public var post4CommentsTitle: String? - - public init(commentId: String, - content: String, - post4CommentsPostId: String? = nil, - post4CommentsTitle: String? = nil) { - self.init(commentId: commentId, + + public init( + commentId: String, + content: String, + post4CommentsPostId: String? = nil, + post4CommentsTitle: String? = nil + ) { + self.init( + commentId: commentId, content: content, createdAt: nil, updatedAt: nil, post4CommentsPostId: post4CommentsPostId, - post4CommentsTitle: post4CommentsTitle) + post4CommentsTitle: post4CommentsTitle + ) } - internal init(commentId: String, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - post4CommentsPostId: String? = nil, - post4CommentsTitle: String? = nil) { + init( + commentId: String, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + post4CommentsPostId: String? = nil, + post4CommentsTitle: String? = nil + ) { self.commentId = commentId self.content = content self.createdAt = createdAt @@ -34,4 +47,4 @@ public struct Comment4: Model { self.post4CommentsPostId = post4CommentsPostId self.post4CommentsTitle = post4CommentsTitle } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4+Schema.swift index 29a8d55288..1f104c79fe 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Post4 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post4 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case postId case title case comments case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post4 = Post4.keys - + model.pluralName = "Post4s" - + model.attributes( .index(fields: ["postId", "title"], name: nil), .primaryKey(fields: [post4.postId, post4.title]) ) - + model.fields( .field(post4.postId, is: .required, ofType: .string), .field(post4.title, is: .required, ofType: .string), @@ -33,10 +40,10 @@ extension Post4 { .field(post4.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Post4: ModelIdentifiable { @@ -44,10 +51,12 @@ extension Post4: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Post4.IdentifierProtocol { - public static func identifier(postId: String, - title: String) -> Self { - .make(fields:[(name: "postId", value: postId), (name: "title", value: title)]) +public extension Post4.IdentifierProtocol { + static func identifier( + postId: String, + title: String + ) -> Self { + .make(fields: [(name: "postId", value: postId), (name: "title", value: title)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4.swift index a50849704b..1d08640c37 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL7/Post4.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -8,25 +15,31 @@ public struct Post4: Model { public var comments: List? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(postId: String, - title: String, - comments: List? = []) { - self.init(postId: postId, + + public init( + postId: String, + title: String, + comments: List? = [] + ) { + self.init( + postId: postId, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(postId: String, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + postId: String, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.postId = postId self.title = title self.comments = comments self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5SnapshotTests.swift index 4f49eda389..13736975dc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5SnapshotTests.swift @@ -5,20 +5,22 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadProjectTeam5Tests { - + func testProjectSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam5Models()) continueAfterFailure = true - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) // Create let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) let createDocument = """ @@ -48,7 +50,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: project, modelSchema: Project.schema) let updateDocument = """ @@ -78,7 +80,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: project, modelSchema: Project.schema) let deleteDocument = """ @@ -108,7 +110,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -134,7 +136,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -160,7 +162,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -186,7 +188,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Project.self) let syncDocument = """ @@ -217,12 +219,12 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testTeamSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam5Models()) continueAfterFailure = true let team = Team(teamId: UUID().uuidString, name: "name") - + // Create let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) let createDocument = """ @@ -252,7 +254,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: team, modelSchema: Team.schema) let updateDocument = """ @@ -282,7 +284,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: team, modelSchema: Team.schema) let deleteDocument = """ @@ -312,7 +314,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Team.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -336,7 +338,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -360,7 +362,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -384,7 +386,7 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Team.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5Tests.swift index ade3115dac..ec1c113f3f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/AWSDataStoreLazyLoadProjectTeam5Tests.swift @@ -5,70 +5,78 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: ProjectTeam5Models()) try await startAndWaitForReady() printDBPath() } - + func testSaveTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam5Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await createAndWaitForSync(project) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) let savedProject = try await createAndWaitForSync(project) let queriedProject = try await query(for: savedProject) assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await createAndWaitForSync(project2) let queriedProject2 = try await query(for: savedProject2) assertProjectDoesNotContainTeam(queriedProject2) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - teamId: team.teamId, - teamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + teamId: team.teamId, + teamName: team.name + ) let savedProject3 = try await createAndWaitForSync(project3) let queriedProject3 = try await query(for: savedProject3) assertProject(queriedProject3, hasTeam: savedTeam) } - + // One-to-One relationships do not create a foreign key for the Team or Project table // So the LazyModel does not have the FK value to be instantiated as metadata for lazy loading. // We only assert the FK fields on the Project exist and are equal to the Team's PK. @@ -76,17 +84,17 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { XCTAssertEqual(project.teamId, team.teamId) XCTAssertEqual(project.teamName, team.name) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.teamId) XCTAssertNil(project.teamName) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) assertProject(savedProject, hasTeam: savedTeam) @@ -95,13 +103,13 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { let updatedProject = try await updateAndWaitForSync(project) assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam5Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await createAndWaitForSync(project) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) var queriedProject = try await query(for: savedProject) @@ -110,7 +118,7 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -124,7 +132,7 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNoTeam = try await updateAndWaitForSync(queriedProject) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -141,7 +149,7 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { _ = savedProjectWithNewTeam assertProject(queriedProject, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -150,7 +158,7 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam5Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -159,37 +167,39 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedProject) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam5Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) let savedProject = try await createAndWaitForSync(project) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedProject) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testObserveProject() async throws { await setup(withModels: ProjectTeam5Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Project.self) Task { @@ -203,18 +213,18 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveTeam() async throws { await setup(withModels: ProjectTeam5Models()) try await startAndWaitForReady() @@ -227,30 +237,30 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { version == 1, let receivedTeam = try? mutationEvent.decodeModel(as: Team.self), receivedTeam.teamId == team.teamId { - + mutationEventReceived.fulfill() } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryProject() async throws { await setup(withModels: ProjectTeam5Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Project.self, where: Project.keys.projectId == project.projectId) Task { @@ -261,18 +271,18 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryTeam() async throws { await setup(withModels: ProjectTeam5Models()) try await startAndWaitForReady() @@ -287,24 +297,24 @@ class AWSDataStoreLazyLoadProjectTeam5Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } } extension AWSDataStoreLazyLoadProjectTeam5Tests { - + typealias Project = Project5 typealias Team = Team5 - + struct ProjectTeam5Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -312,12 +322,14 @@ extension AWSDataStoreLazyLoadProjectTeam5Tests { ModelRegistry.register(modelType: Team5.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5+Schema.swift index c3b1a54883..d905b055ea 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project5 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Project5 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project5 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let project5 = Project5.keys - + model.pluralName = "Project5s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project5.projectId, project5.name]) ) - + model.fields( .field(project5.projectId, is: .required, ofType: .string), .field(project5.name, is: .required, ofType: .string), @@ -37,10 +44,10 @@ extension Project5 { .field(project5.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project5: ModelIdentifiable { @@ -48,10 +55,12 @@ extension Project5: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project5.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project5.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5.swift index 3f72dfb0f0..60bec5a586 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Project5.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project5: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team5? { get async throws { try await _team.get() @@ -15,27 +22,33 @@ public struct Project5: Model { public var teamName: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(projectId: String, - name: String, - team: Team5? = nil, - teamId: String? = nil, - teamName: String? = nil) { - self.init(projectId: projectId, - name: name, - team: team, - teamId: teamId, - teamName: teamName, - createdAt: nil, - updatedAt: nil) + + public init( + projectId: String, + name: String, + team: Team5? = nil, + teamId: String? = nil, + teamName: String? = nil + ) { + self.init( + projectId: projectId, + name: name, + team: team, + teamId: teamId, + teamName: teamName, + createdAt: nil, + updatedAt: nil + ) } - internal init(projectId: String, - name: String, - team: Team5? = nil, - teamId: String? = nil, - teamName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + projectId: String, + name: String, + team: Team5? = nil, + teamId: String? = nil, + teamName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -44,22 +57,22 @@ public struct Project5: Model { self.createdAt = createdAt self.updatedAt = updatedAt } - + public mutating func setTeam(_ team: Team5) { - self._team = LazyReference(team) + _team = LazyReference(team) } - + public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - teamId = try values.decode(String?.self, forKey: .teamId) - teamName = try values.decode(String?.self, forKey: .teamName) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.teamId = try values.decode(String?.self, forKey: .teamId) + self.teamName = try values.decode(String?.self, forKey: .teamName) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(projectId, forKey: .projectId) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5+Schema.swift index e27f517b2c..b80f7f952b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5+Schema.swift @@ -1,30 +1,37 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team5 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team5 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case teamId case name case project case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team5 = Team5.keys - + model.pluralName = "Team5s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team5.teamId, team5.name]) ) - + model.fields( .field(team5.teamId, is: .required, ofType: .string), .field(team5.name, is: .required, ofType: .string), @@ -33,10 +40,10 @@ extension Team5 { .field(team5.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team5: ModelIdentifiable { @@ -44,10 +51,12 @@ extension Team5: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team5.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team5.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5.swift index c3c868ed8a..d72b177b7c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL8/Team5.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Team5: Model { public let teamId: String public let name: String - internal var _project: LazyReference + var _project: LazyReference public var project: Project5? { get async throws { try await _project.get() @@ -13,37 +20,43 @@ public struct Team5: Model { } public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String, - project: Project5? = nil) { - self.init(teamId: teamId, - name: name, - project: project, - createdAt: nil, - updatedAt: nil) + + public init( + teamId: String, + name: String, + project: Project5? = nil + ) { + self.init( + teamId: teamId, + name: name, + project: project, + createdAt: nil, + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - project: Project5? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + project: Project5? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self._project = LazyReference(project) self.createdAt = createdAt self.updatedAt = updatedAt } - + public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - teamId = try values.decode(String.self, forKey: .teamId) - name = try values.decode(String.self, forKey: .name) - _project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.teamId = try values.decode(String.self, forKey: .teamId) + self.name = try values.decode(String.self, forKey: .name) + self._project = try values.decodeIfPresent(LazyReference.self, forKey: .project) ?? LazyReference(identifiers: nil) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(teamId, forKey: .teamId) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6SnapshotTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6SnapshotTests.swift index 923ac67866..e2bc3cbb4b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6SnapshotTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6SnapshotTests.swift @@ -5,20 +5,22 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify extension AWSDataStoreLazyLoadProjectTeam6Tests { - + func testProjectSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam6Models()) continueAfterFailure = true - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) // Create let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) let createDocument = """ @@ -48,7 +50,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: project, modelSchema: Project.schema) let updateDocument = """ @@ -78,7 +80,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: project, modelSchema: Project.schema) let deleteDocument = """ @@ -108,7 +110,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onCreate) let onCreateDocument = """ @@ -134,7 +136,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -160,7 +162,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Project.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -186,7 +188,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Project.self) let syncDocument = """ @@ -217,12 +219,12 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { """ XCTAssertEqual(syncRequest.document, syncDocument) } - + func testTeamSelectionSets() { setUpModelRegistrationOnly(withModels: ProjectTeam6Models()) continueAfterFailure = true let team = Team(teamId: UUID().uuidString, name: "name") - + // Create let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) let createDocument = """ @@ -240,7 +242,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(createRequest.document, createDocument) - + // Update let updateRequest = GraphQLRequest.updateMutation(of: team, modelSchema: Team.schema) let updateDocument = """ @@ -258,7 +260,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(updateRequest.document, updateDocument) - + // Delete let deleteRequest = GraphQLRequest.deleteMutation(of: team, modelSchema: Team.schema) let deleteDocument = """ @@ -276,7 +278,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(deleteRequest.document, deleteDocument) - + // onCreate let onCreateRequest = GraphQLRequest.subscription(to: Team.schema, subscriptionType: .onCreate) let onCreateDocument = """ @@ -294,7 +296,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onCreateRequest.document, onCreateDocument) - + // onUpdate let onUpdateRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onUpdate) let onUpdateDocument = """ @@ -312,7 +314,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onUpdateRequest.document, onUpdateDocument) - + // onDelete let onDeleteRequest = GraphQLRequest.subscription(to: Team.self, subscriptionType: .onDelete) let onDeleteDocument = """ @@ -330,7 +332,7 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { } """ XCTAssertEqual(onDeleteRequest.document, onDeleteDocument) - + // SyncQuery let syncRequest = GraphQLRequest.syncQuery(modelType: Team.self) let syncDocument = """ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6Tests.swift index 574f2c9d55..aeee6facfa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/AWSDataStoreLazyLoadProjectTeam6Tests.swift @@ -5,70 +5,78 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest -@testable import Amplify import AWSPluginsCore +@testable import Amplify class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { - + func testStart() async throws { await setup(withModels: ProjectTeam6Models()) try await startAndWaitForReady() printDBPath() } - + func testSaveTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) try await assertModelExists(savedTeam) } - + func testSaveProject() async throws { await setup(withModels: ProjectTeam6Models()) - let project = Project(projectId: UUID().uuidString, - name: "name") + let project = Project( + projectId: UUID().uuidString, + name: "name" + ) let savedProject = try await createAndWaitForSync(project) try await assertModelExists(savedProject) assertProjectDoesNotContainTeam(savedProject) } - + func testSaveProjectWithTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + // Project initializer variation #1 (pass both team reference and fields in) - let project = Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + let project = Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) let savedProject = try await createAndWaitForSync(project) let queriedProject = try await query(for: savedProject) assertProject(queriedProject, hasTeam: savedTeam) - + // Project initializer variation #2 (pass only team reference) - let project2 = Project(projectId: UUID().uuidString, - name: "name", - team: team) + let project2 = Project( + projectId: UUID().uuidString, + name: "name", + team: team + ) let savedProject2 = try await createAndWaitForSync(project2) let queriedProject2 = try await query(for: savedProject2) assertProjectDoesNotContainTeam(queriedProject2) - + // Project initializer variation #3 (pass fields in) - let project3 = Project(projectId: UUID().uuidString, - name: "name", - teamId: team.teamId, - teamName: team.name) + let project3 = Project( + projectId: UUID().uuidString, + name: "name", + teamId: team.teamId, + teamName: team.name + ) let savedProject3 = try await createAndWaitForSync(project3) let queriedProject3 = try await query(for: savedProject3) assertProject(queriedProject3, hasTeam: savedTeam) } - + // One-to-One relationships do not create a foreign key for the Team or Project table // So the LazyModel does not have the FK value to be instantiated as metadata for lazy loading. // We only assert the FK fields on the Project exist and are equal to the Team's PK. @@ -76,17 +84,17 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { XCTAssertEqual(project.teamId, team.teamId) XCTAssertEqual(project.teamName, team.name) } - + func assertProjectDoesNotContainTeam(_ project: Project) { XCTAssertNil(project.teamId) XCTAssertNil(project.teamName) } - + func testSaveProjectWithTeamThenUpdate() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) - + let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) assertProject(savedProject, hasTeam: savedTeam) @@ -95,13 +103,13 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { let updatedProject = try await updateAndWaitForSync(project) assertProject(updatedProject, hasTeam: savedTeam) } - + func testSaveProjectWithoutTeamUpdateProjectWithTeam() async throws { await setup(withModels: ProjectTeam6Models()) let project = Project(projectId: UUID().uuidString, name: "name") let savedProject = try await createAndWaitForSync(project) assertProjectDoesNotContainTeam(savedProject) - + let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) var queriedProject = try await query(for: savedProject) @@ -110,7 +118,7 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(savedProjectWithNewTeam, hasTeam: savedTeam) } - + func testSaveTeamSaveProjectWithTeamUpdateProjectToNoTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -124,7 +132,7 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNoTeam = try await updateAndWaitForSync(queriedProject) assertProjectDoesNotContainTeam(savedProjectWithNoTeam) } - + func testSaveProjectWithTeamUpdateProjectToNewTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -140,7 +148,7 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { let savedProjectWithNewTeam = try await updateAndWaitForSync(queriedProject) assertProject(queriedProject, hasTeam: savedNewTeam) } - + func testDeleteTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") @@ -149,7 +157,7 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testDeleteProject() async throws { await setup(withModels: ProjectTeam6Models()) let project = Project(projectId: UUID().uuidString, name: "name") @@ -158,33 +166,33 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { try await deleteAndWaitForSync(savedProject) try await assertModelDoesNotExist(savedProject) } - + func testDeleteProjectWithTeam() async throws { await setup(withModels: ProjectTeam6Models()) let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) let savedProject = try await createAndWaitForSync(project) - + try await assertModelExists(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedProject) - + try await assertModelDoesNotExist(savedProject) try await assertModelExists(savedTeam) - + try await deleteAndWaitForSync(savedTeam) try await assertModelDoesNotExist(savedTeam) } - + func testObserveProject() async throws { await setup(withModels: ProjectTeam6Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let mutationEventReceived = expectation(description: "Received mutation event") let mutationEvents = Amplify.DataStore.observe(Project.self) Task { @@ -198,18 +206,18 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveTeam() async throws { await setup(withModels: ProjectTeam6Models()) try await startAndWaitForReady() @@ -226,25 +234,25 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [mutationEventReceived], timeout: 60) mutationEvents.cancel() } - + func testObserveQueryProject() async throws { await setup(withModels: ProjectTeam6Models()) try await startAndWaitForReady() let team = Team(teamId: UUID().uuidString, name: "name") let savedTeam = try await createAndWaitForSync(team) let project = initializeProjectWithTeam(team) - + let snapshotReceived = expectation(description: "Received query snapshot") let querySnapshots = Amplify.DataStore.observeQuery(for: Project.self, where: Project.keys.projectId == project.projectId) Task { @@ -255,18 +263,18 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: project, modelSchema: Project.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } - + func testObserveQueryTeam() async throws { await setup(withModels: ProjectTeam6Models()) try await startAndWaitForReady() @@ -281,24 +289,24 @@ class AWSDataStoreLazyLoadProjectTeam6Tests: AWSDataStoreLazyLoadBaseTest { } } } - + let createRequest = GraphQLRequest.createMutation(of: team, modelSchema: Team.schema) do { _ = try await Amplify.API.mutate(request: createRequest) } catch { XCTFail("Failed to send mutation request \(error)") } - + await fulfillment(of: [snapshotReceived], timeout: 60) querySnapshots.cancel() } } extension AWSDataStoreLazyLoadProjectTeam6Tests { - + typealias Project = Project6 typealias Team = Team6 - + struct ProjectTeam6Models: AmplifyModelRegistration { public let version: String = "version" func registerModels(registry: ModelRegistry.Type) { @@ -306,12 +314,14 @@ extension AWSDataStoreLazyLoadProjectTeam6Tests { ModelRegistry.register(modelType: Team6.self) } } - + func initializeProjectWithTeam(_ team: Team) -> Project { - return Project(projectId: UUID().uuidString, - name: "name", - team: team, - teamId: team.teamId, - teamName: team.name) + return Project( + projectId: UUID().uuidString, + name: "name", + team: team, + teamId: team.teamId, + teamName: team.name + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6+Schema.swift index 380eecaa91..d87b3977f2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6+Schema.swift @@ -1,10 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Project6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Project6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case projectId case name case team @@ -13,20 +20,20 @@ extension Project6 { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let project6 = Project6.keys - + model.pluralName = "Project6s" - + model.attributes( .index(fields: ["projectId", "name"], name: nil), .primaryKey(fields: [project6.projectId, project6.name]) ) - + model.fields( .field(project6.projectId, is: .required, ofType: .string), .field(project6.name, is: .required, ofType: .string), @@ -37,10 +44,10 @@ extension Project6 { .field(project6.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Project6: ModelIdentifiable { @@ -48,10 +55,12 @@ extension Project6: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Project6.IdentifierProtocol { - public static func identifier(projectId: String, - name: String) -> Self { - .make(fields:[(name: "projectId", value: projectId), (name: "name", value: name)]) +public extension Project6.IdentifierProtocol { + static func identifier( + projectId: String, + name: String + ) -> Self { + .make(fields: [(name: "projectId", value: projectId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6.swift index 797d5f3ec3..c8a0ee3112 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Project6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -5,7 +12,7 @@ import Foundation public struct Project6: Model { public let projectId: String public let name: String - internal var _team: LazyReference + var _team: LazyReference public var team: Team6? { get async throws { try await _team.get() @@ -15,27 +22,33 @@ public struct Project6: Model { public var teamName: String? public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(projectId: String, - name: String, - team: Team6? = nil, - teamId: String? = nil, - teamName: String? = nil) { - self.init(projectId: projectId, - name: name, - team: team, - teamId: teamId, - teamName: teamName, - createdAt: nil, - updatedAt: nil) + + public init( + projectId: String, + name: String, + team: Team6? = nil, + teamId: String? = nil, + teamName: String? = nil + ) { + self.init( + projectId: projectId, + name: name, + team: team, + teamId: teamId, + teamName: teamName, + createdAt: nil, + updatedAt: nil + ) } - internal init(projectId: String, - name: String, - team: Team6? = nil, - teamId: String? = nil, - teamName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + projectId: String, + name: String, + team: Team6? = nil, + teamId: String? = nil, + teamName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.projectId = projectId self.name = name self._team = LazyReference(team) @@ -44,22 +57,22 @@ public struct Project6: Model { self.createdAt = createdAt self.updatedAt = updatedAt } - + public mutating func setTeam(_ team: Team6?) { - self._team = LazyReference(team) + _team = LazyReference(team) } - + public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - projectId = try values.decode(String.self, forKey: .projectId) - name = try values.decode(String.self, forKey: .name) - _team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) - teamId = try values.decode(String?.self, forKey: .teamId) - teamName = try values.decode(String?.self, forKey: .teamName) - createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) - updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) + self.projectId = try values.decode(String.self, forKey: .projectId) + self.name = try values.decode(String.self, forKey: .name) + self._team = try values.decodeIfPresent(LazyReference.self, forKey: .team) ?? LazyReference(identifiers: nil) + self.teamId = try values.decode(String?.self, forKey: .teamId) + self.teamName = try values.decode(String?.self, forKey: .teamName) + self.createdAt = try values.decode(Temporal.DateTime?.self, forKey: .createdAt) + self.updatedAt = try values.decode(Temporal.DateTime?.self, forKey: .updatedAt) } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(projectId, forKey: .projectId) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6+Schema.swift index 477021cd02..4e8fcda622 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6+Schema.swift @@ -1,29 +1,36 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation -extension Team6 { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Team6 { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case teamId case name case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let team6 = Team6.keys - + model.pluralName = "Team6s" - + model.attributes( .index(fields: ["teamId", "name"], name: nil), .primaryKey(fields: [team6.teamId, team6.name]) ) - + model.fields( .field(team6.teamId, is: .required, ofType: .string), .field(team6.name, is: .required, ofType: .string), @@ -31,10 +38,10 @@ extension Team6 { .field(team6.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime) ) } - - public class Path: ModelPath { } - - public static var rootPath: PropertyContainerPath? { Path() } + + class Path: ModelPath { } + + static var rootPath: PropertyContainerPath? { Path() } } extension Team6: ModelIdentifiable { @@ -42,10 +49,12 @@ extension Team6: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier } -extension Team6.IdentifierProtocol { - public static func identifier(teamId: String, - name: String) -> Self { - .make(fields:[(name: "teamId", value: teamId), (name: "name", value: name)]) +public extension Team6.IdentifierProtocol { + static func identifier( + teamId: String, + name: String + ) -> Self { + .make(fields: [(name: "teamId", value: teamId), (name: "name", value: name)]) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6.swift index 88da92235b..3a45fc3f04 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LL9/Team6.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation @@ -7,21 +14,27 @@ public struct Team6: Model { public let name: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(teamId: String, - name: String) { - self.init(teamId: teamId, + + public init( + teamId: String, + name: String + ) { + self.init( + teamId: teamId, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(teamId: String, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + teamId: String, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.teamId = teamId self.name = name self.createdAt = createdAt self.updatedAt = updatedAt } -} \ No newline at end of file +} diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AWSDataStoreLazyLoadBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AWSDataStoreLazyLoadBaseTest.swift index 7d8fa69431..08c9f517e4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AWSDataStoreLazyLoadBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AWSDataStoreLazyLoadBaseTest.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSAPIPlugin +import AWSPluginsCore +import Combine import Foundation import XCTest -import Combine @testable import AWSDataStorePlugin -import AWSPluginsCore -import AWSAPIPlugin #if !os(watchOS) @testable import DataStoreHostApp @@ -19,15 +19,15 @@ import AWSAPIPlugin class AWSDataStoreLazyLoadBaseTest: XCTestCase { var amplifyConfig: AmplifyConfiguration! - + var apiOnly: Bool = false var modelsOnly: Bool = false var clearOnTearDown: Bool = false - + override func setUp() { continueAfterFailure = false } - + override func tearDown() async throws { if !(apiOnly || modelsOnly) { try await clearDataStore() @@ -35,19 +35,19 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { await Amplify.reset() try await Task.sleep(seconds: 1) } - + func setupConfig() { let basePath = "testconfiguration" let baseFileName = "AWSDataStoreCategoryPluginLazyLoadIntegrationTests" let configFile = "\(basePath)/\(baseFileName)-amplifyconfiguration" - + do { amplifyConfig = try TestConfigHelper.retrieveAmplifyConfiguration(forResource: configFile) } catch { XCTFail("Error during setup: \(error)") } } - + func apiEndpointName() throws -> String { guard let apiPlugin = amplifyConfig.api?.plugins["awsAPIPlugin"], case .object(let value) = apiPlugin else { @@ -55,68 +55,78 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { } return value.keys.first! } - + /// Setup DataStore with given models /// - Parameter models: DataStore models - func setup(withModels models: AmplifyModelRegistration, - logLevel: LogLevel = .verbose, - clearOnTearDown: Bool = false) async { + func setup( + withModels models: AmplifyModelRegistration, + logLevel: LogLevel = .verbose, + clearOnTearDown: Bool = false + ) async { self.clearOnTearDown = clearOnTearDown do { setupConfig() Amplify.Logging.logLevel = logLevel - + #if os(watchOS) try Amplify.add(plugin: AWSDataStorePlugin( modelRegistration: models, configuration: .custom( errorHandler: { error in Amplify.Logging.error("DataStore ErrorHandler error: \(error)")}, syncMaxRecords: 100, - disableSubscriptions: { false }))) + disableSubscriptions: { false } + ) + )) #else try Amplify.add(plugin: AWSDataStorePlugin( modelRegistration: models, configuration: .custom( errorHandler: { error in Amplify.Logging.error("DataStore ErrorHandler error: \(error)")}, - syncMaxRecords: 100))) + syncMaxRecords: 100 + ) + )) #endif try Amplify.add(plugin: AWSAPIPlugin(sessionFactory: AmplifyURLSessionFactory())) try Amplify.configure(amplifyConfig) - + try await Amplify.DataStore.start() } catch { XCTFail("Error during setup: \(error)") } } - - func setUpDataStoreOnly(withModels models: AmplifyModelRegistration, - logLevel: LogLevel = .verbose, - clearOnTearDown: Bool = false) async { + + func setUpDataStoreOnly( + withModels models: AmplifyModelRegistration, + logLevel: LogLevel = .verbose, + clearOnTearDown: Bool = false + ) async { self.clearOnTearDown = clearOnTearDown do { setupConfig() Amplify.Logging.logLevel = logLevel - + #if os(watchOS) try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, configuration: .subscriptionsDisabled)) #else try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models)) #endif - + try Amplify.configure(amplifyConfig) - + try await deleteMutationEvents() } catch { XCTFail("Error during setup: \(error)") } } - - func setUpModelRegistrationOnly(withModels models: AmplifyModelRegistration, - logLevel: LogLevel = .verbose) { + + func setUpModelRegistrationOnly( + withModels models: AmplifyModelRegistration, + logLevel: LogLevel = .verbose + ) { modelsOnly = true models.registerModels(registry: ModelRegistry.self) } - + func setupAPIOnly(withModels models: AmplifyModelRegistration, logLevel: LogLevel = .verbose) async { apiOnly = true do { @@ -128,15 +138,15 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { XCTFail("Error during setup: \(error)") } } - + func deleteMutationEvents() async throws { try await Amplify.DataStore.delete(MutationEvent.self, where: QueryPredicateConstant.all) } - + func clearDataStore() async throws { try await Amplify.DataStore.clear() } - + func startAndWaitForReady() async throws { var requests: Set = [] let dataStoreReady = expectation(description: "DataStore `ready` event received") @@ -153,16 +163,16 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { try await startDataStore() await fulfillment(of: [dataStoreReady], timeout: 60) } - + func startDataStore() async throws { try await Amplify.DataStore.start() } - + func printDBPath() { let dbPath = DataStoreDebugger.dbFilePath print("DBPath: \(dbPath)") } - + @discardableResult func createAndWaitForSync(_ model: M) async throws -> M { var requests: Set = [] @@ -182,7 +192,7 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { await fulfillment(of: [modelSynced], timeout: 100) return savedModel } - + @discardableResult func updateAndWaitForSync(_ model: M, assertVersion: Int? = nil) async throws -> M { var requests: Set = [] @@ -195,7 +205,7 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { .filter { $0.mutationType == MutationEvent.MutationType.update.rawValue } .compactMap(\.version) .filter { version in - assertVersion.map({ $0 == version }) ?? true + assertVersion.map { $0 == version } ?? true } .sink { _ in modelSynced.fulfill() @@ -207,7 +217,7 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { return updatedModel } - func deleteAndWaitForSync(_ model: M) async throws { + func deleteAndWaitForSync(_ model: some Model) async throws { var requests: Set = [] let modelSynced = expectation(description: "delete model was synced successfully") let dataStoreEvents = HubPayload.EventName.DataStore.self @@ -224,13 +234,13 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { try await Amplify.DataStore.delete(model) await fulfillment(of: [modelSynced], timeout: 10) } - + enum AssertListState { case isNotLoaded(associatedIds: [String], associatedFields: [String]) case isLoaded(count: Int) } - - func assertList(_ list: List, state: AssertListState) { + + func assertList(_ list: List, state: AssertListState) { switch state { case .isNotLoaded(let expectedAssociatedIds, let expectedAssociatedFields): if case .notLoaded(let associatedIdentifiers, let associatedFields) = list.listProvider.getState() { @@ -247,14 +257,16 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { } } } - + enum AssertLazyModelState { case notLoaded(identifiers: [LazyReferenceIdentifier]?) case loaded(model: M?) } - - func assertLazyReference(_ lazyModel: LazyReference, - state: AssertLazyModelState) { + + func assertLazyReference( + _ lazyModel: LazyReference, + state: AssertLazyModelState + ) { switch state { case .notLoaded(let expectedIdentifiers): if case .notLoaded(let identifiers) = lazyModel.modelProvider.getState() { @@ -264,7 +276,7 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { } case .loaded(let expectedModel): if case .loaded(let model) = lazyModel.modelProvider.getState() { - guard let expectedModel = expectedModel, let model = model else { + guard let expectedModel, let model else { XCTAssertNil(model) return } @@ -274,40 +286,48 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { } } } - - func assertModelExists(_ model: M) async throws { + + func assertModelExists(_ model: some Model) async throws { let modelExists = try await modelExists(model) XCTAssertTrue(modelExists) } - - func assertModelDoesNotExist(_ model: M) async throws { + + func assertModelDoesNotExist(_ model: some Model) async throws { let modelExists = try await modelExists(model) XCTAssertFalse(modelExists) } - + func modelExists(_ model: M) async throws -> Bool { let identifierName = model.schema.primaryKey.sqlName let queryPredicate: QueryPredicate = field(identifierName).eq(model.identifier) - - let queriedModels = try await Amplify.DataStore.query(M.self, - where: queryPredicate) - let metadataId = MutationSyncMetadata.identifier(modelName: model.modelName, - modelId: model.identifier) - guard let metadata = try await Amplify.DataStore.query(MutationSyncMetadata.self, - byId: metadataId) else { + + let queriedModels = try await Amplify.DataStore.query( + M.self, + where: queryPredicate + ) + let metadataId = MutationSyncMetadata.identifier( + modelName: model.modelName, + modelId: model.identifier + ) + guard let metadata = try await Amplify.DataStore.query( + MutationSyncMetadata.self, + byId: metadataId + ) else { XCTFail("Could not retrieve metadata for model \(model)") throw "Could not retrieve metadata for model \(model)" } - + return !(metadata.deleted && queriedModels.isEmpty) } - + func query(for model: M) async throws -> M { let identifierName = model.schema.primaryKey.sqlName let queryPredicate: QueryPredicate = field(identifierName).eq(model.identifier) - - let queriedModels = try await Amplify.DataStore.query(M.self, - where: queryPredicate) + + let queriedModels = try await Amplify.DataStore.query( + M.self, + where: queryPredicate + ) if queriedModels.count > 1 { XCTFail("Expected to find one model, found \(queriedModels.count). \(queriedModels)") throw "Expected to find one model, found \(queriedModels.count). \(queriedModels)" @@ -320,21 +340,21 @@ class AWSDataStoreLazyLoadBaseTest: XCTestCase { } } -struct DataStoreDebugger { - +enum DataStoreDebugger { + static var dbFilePath: URL? { getAdapter()?.dbFilePath } - + static func getAdapter() -> SQLiteStorageEngineAdapter? { if let dataStorePlugin = tryGetPlugin(), let storageEngine = dataStorePlugin.storageEngine as? StorageEngine, let adapter = storageEngine.storageAdapter as? SQLiteStorageEngineAdapter { return adapter } - + print("Could not get `SQLiteStorageEngineAdapter` from DataStore") return nil } - + static func tryGetPlugin() -> AWSDataStorePlugin? { do { return try Amplify.DataStore.getPlugin(for: "awsDataStorePlugin") as? AWSDataStorePlugin diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AmplifyModels.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AmplifyModels.swift index fa01b38420..798732052f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AmplifyModels.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginLazyLoadTests/LazyLoadBase/AmplifyModels.swift @@ -1,12 +1,19 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + // swiftlint:disable all import Amplify import Foundation // Contains the set of classes that conforms to the `Model` protocol. -final public class AmplifyModels: AmplifyModelRegistration { +public final class AmplifyModels: AmplifyModelRegistration { public let version: String = "248b0ffa3d44f144554beab3bf489b20" - + public func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post4V2.self) ModelRegistry.register(modelType: Comment4V2.self) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreAuthBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreAuthBaseTest.swift index 155915a31b..0a61ea2fe6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreAuthBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreAuthBaseTest.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import XCTest -import Combine +import AWSCognitoAuthPlugin import AWSDataStorePlugin import AWSPluginsCore +import Combine +import Foundation +import XCTest @testable import AWSAPIPlugin -import AWSCognitoAuthPlugin #if !os(watchOS) @testable import DataStoreHostApp @@ -48,13 +48,13 @@ class DataStoreAuthBaseTestURLSessionFactory: URLSessionBehaviorFactory { result.insert(.apiKey) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, case let .success(claims) = AWSAuthService().getTokenClaims(tokenString: authHeaderValue), let cognitoIss = claims["iss"] as? String, cognitoIss.contains("cognito") { result.insert(.amazonCognitoUserPools) } - if let authHeaderValue = authHeaderValue, + if let authHeaderValue, authHeaderValue.starts(with: "AWS4-HMAC-SHA256") { result.insert(.awsIAM) } @@ -89,9 +89,11 @@ class DataStoreAuthBaseTestURLSessionFactory: URLSessionBehaviorFactory { configuration.tlsMaximumSupportedProtocolVersion = .TLSv13 configuration.protocolClasses?.insert(Sniffer.self, at: 0) - let session = URLSession(configuration: configuration, - delegate: urlSessionDelegate, - delegateQueue: nil) + let session = URLSession( + configuration: configuration, + delegate: urlSessionDelegate, + delegateQueue: nil + ) return AmplifyURLSession(session: session) } @@ -203,9 +205,11 @@ class AWSDataStoreAuthBaseTest: XCTestCase { #else let datastoreConfig = DataStoreConfiguration.custom(authModeStrategy: testType.authStrategy) #endif - - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: datastoreConfig)) + + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: datastoreConfig + )) let apiPlugin = apiPluginFactory() @@ -238,40 +242,46 @@ class AWSDataStoreAuthBaseTest: XCTestCase { extension AWSDataStoreAuthBaseTest { /// Signin given user /// - Parameter user - func signIn(user: TestUser?, - file: StaticString = #file, - line: UInt = #line) async { - guard let user = user else { + func signIn( + user: TestUser?, + file: StaticString = #file, + line: UInt = #line + ) async { + guard let user else { XCTFail("Invalid user", file: file, line: line) return } let signInInvoked = expectation(description: "sign in completed") do { - _ = try await Amplify.Auth.signIn(username: user.username, - password: user.password, - options: nil) + _ = try await Amplify.Auth.signIn( + username: user.username, + password: user.password, + options: nil + ) signInInvoked.fulfill() - } catch(let error) { + } catch (let error) { XCTFail("Signin failure \(error)", file: file, line: line) signInInvoked.fulfill() // won't count as pass } await fulfillment(of: [signInInvoked], timeout: TestCommonConstants.networkTimeout) - + let signedIn = await isSignedIn() XCTAssert(signedIn, file: file, line: line) } /// Signout current signed-in user - func signOut(file: StaticString = #file, - line: UInt = #line) async { + func signOut( + file: StaticString = #file, + line: UInt = #line + ) async { let signoutInvoked = expectation(description: "sign out completed") Task { _ = await Amplify.Auth.signOut() signoutInvoked.fulfill() } - + await fulfillment(of: [signoutInvoked], timeout: TestCommonConstants.networkTimeout) - + let signedIn = await isSignedIn() XCTAssert(!signedIn, file: file, line: line) } @@ -284,10 +294,10 @@ extension AWSDataStoreAuthBaseTest { let authSession = try await Amplify.Auth.fetchAuthSession() resultOptional = authSession.isSignedIn checkIsSignedInCompleted.fulfill() - } catch(let error) { + } catch (let error) { fatalError("Failed to get auth session \(error)") } - + await fulfillment(of: [checkIsSignedInCompleted], timeout: TestCommonConstants.networkTimeout) guard let result = resultOptional else { XCTFail("Could not get isSignedIn for user") @@ -313,7 +323,7 @@ extension AWSDataStoreAuthBaseTest { case .failure(let error): XCTFail("Failed to get auth session \(error)") } - } catch(let error) { + } catch (let error) { XCTFail("Failed to get auth session \(error)") } @@ -342,7 +352,7 @@ extension AWSDataStoreAuthBaseTest { case .failure(let error): XCTFail("Failed to get auth session \(error)") } - } catch(let error) { + } catch (let error) { XCTFail("Failed to get auth session \(error)") } await fulfillment(of: [retrieveIdentityCompleted], timeout: TestCommonConstants.networkTimeout) @@ -354,10 +364,12 @@ extension AWSDataStoreAuthBaseTest { return result } - func queryModel(_ model: M.Type, - byId id: String, - file: StaticString = #file, - line: UInt = #line) async -> M? { + func queryModel( + _ model: M.Type, + byId id: String, + file: StaticString = #file, + line: UInt = #line + ) async -> M? { var queriedModel: M? let queriedInvoked = expectation(description: "Model queried") @@ -365,10 +377,10 @@ extension AWSDataStoreAuthBaseTest { let model = try await Amplify.DataStore.query(M.self, byId: id) queriedModel = model queriedInvoked.fulfill() - } catch(let error) { + } catch (let error) { XCTFail("Failed to query model \(error)", file: file, line: line) } - + await fulfillment(of: [queriedInvoked], timeout: TestCommonConstants.networkTimeout) return queriedModel } @@ -381,9 +393,11 @@ extension AWSDataStoreAuthBaseTest { /// - modelType: model type /// - expectation: success XCTestExpectation /// - onFailure: on failure callback - func assertQuerySuccess(modelType: M.Type, - _ expectations: AuthTestExpectations, - onFailure: @escaping (_ error: DataStoreError) -> Void) async { + func assertQuerySuccess( + modelType: (some Model).Type, + _ expectations: AuthTestExpectations, + onFailure: @escaping (_ error: DataStoreError) -> Void + ) async { Amplify.Publisher.create { try await Amplify.DataStore.query(modelType) }.sink { @@ -395,14 +409,18 @@ extension AWSDataStoreAuthBaseTest { XCTAssertNotNil(posts) expectations.query.fulfill() }.store(in: &requests) - await fulfillment(of: [expectations.query], - timeout: 60) + await fulfillment( + of: [expectations.query], + timeout: 60 + ) } /// Asserts that DataStore is in a ready state and subscriptions are established /// - Parameter events: DataStore Hub events - func assertDataStoreReady(_ expectations: AuthTestExpectations, - expectedModelSynced: Int = 1) async { + func assertDataStoreReady( + _ expectations: AuthTestExpectations, + expectedModelSynced: Int = 1 + ) async { var modelSyncedCount = 0 let dataStoreEvents = HubPayload.EventName.DataStore.self Amplify @@ -430,13 +448,17 @@ extension AWSDataStoreAuthBaseTest { do { try await Amplify.DataStore.start() - } catch(let error) { + } catch (let error) { XCTFail("Failure due to error: \(error)") } - await fulfillment(of: [expectations.subscriptionsEstablished, - expectations.modelsSynced, - expectations.ready], - timeout: 60) + await fulfillment( + of: [ + expectations.subscriptionsEstablished, + expectations.modelsSynced, + expectations.ready + ], + timeout: 60 + ) } /// Assert that a save and a delete mutation complete successfully. @@ -444,9 +466,11 @@ extension AWSDataStoreAuthBaseTest { /// - model: model instance saved and then deleted /// - expectations: test expectations /// - onFailure: failure callback - func assertMutations(model: M, - _ expectations: AuthTestExpectations, - onFailure: @escaping (_ error: DataStoreError) -> Void) async { + func assertMutations( + model: some Model, + _ expectations: AuthTestExpectations, + onFailure: @escaping (_ error: DataStoreError) -> Void + ) async { Amplify .Hub .publisher(for: .dataStore) @@ -497,7 +521,7 @@ extension AWSDataStoreAuthBaseTest { await fulfillment(of: [expectations.mutationDelete, expectations.mutationDeleteProcessed], timeout: 60) } - + func assertUsedAuthTypes( testId: String, authTypes: [AWSAuthorizationType], @@ -509,7 +533,7 @@ extension AWSDataStoreAuthBaseTest { DataStoreAuthBaseTestURLSessionFactory.subject .filter { $0.0 == testId } .map { $0.1 } - .collect(.byTime(DispatchQueue.global(), .milliseconds(3500))) + .collect(.byTime(DispatchQueue.global(), .milliseconds(3_500))) .sink { let result = $0.reduce(Set()) { partialResult, data in partialResult.union(data) @@ -534,11 +558,12 @@ extension AWSDataStoreAuthBaseTest { var mutationDeleteProcessed: XCTestExpectation var ready: XCTestExpectation var expectations: [XCTestExpectation] { - return [subscriptionsEstablished, - modelsSynced, - query, - mutationSave, - mutationSaveProcessed + return [ + subscriptionsEstablished, + modelsSynced, + query, + mutationSave, + mutationSaveProcessed ] } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthCombinationTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthCombinationTests.swift index 9ba5f8e61a..a32789dad4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthCombinationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthCombinationTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @@ -17,8 +17,10 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { /// When: DataStore start is called /// Then: DataStore is successfully initialized. func testDataStoreReadyState() async { - await setup(withModels: PrivatePublicComboModels(), - testType: .multiAuth) + await setup( + withModels: PrivatePublicComboModels(), + testType: .multiAuth + ) await signIn(user: user1) let expectations = makeExpectations() @@ -31,7 +33,7 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { do { try await Amplify.DataStore.start() startExpectation.fulfill() - } catch(let error) { + } catch (let error) { XCTFail("DataStore start failure \(error)") } } @@ -44,12 +46,13 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { expectations.mutationDeleteProcessed.fulfill() await fulfillment(of: [ - startExpectation, - expectations.query, - expectations.mutationSave, - expectations.mutationSaveProcessed, - expectations.mutationDelete, - expectations.mutationDeleteProcessed], timeout: TestCommonConstants.networkTimeout) + startExpectation, + expectations.query, + expectations.mutationSave, + expectations.mutationSaveProcessed, + expectations.mutationDelete, + expectations.mutationDeleteProcessed + ], timeout: TestCommonConstants.networkTimeout) } /// Given: a user signed in with IAM @@ -59,9 +62,11 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { /// or PrivatePublicComboUPPost are sent with IAM auth for authenticated users. func testOperationsForPrivatePublicComboUPPost() async { let testId = UUID().uuidString - await setup(withModels: PrivatePublicComboModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePublicComboModels(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -70,14 +75,19 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePublicComboUPPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicComboUPPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicComboUPPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicComboUPPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -93,9 +103,11 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { let testId = UUID().uuidString let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey, .amazonCognitoUserPools]) - await setup(withModels: PrivatePublicComboModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePublicComboModels(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -103,15 +115,20 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { await assertDataStoreReady(expectations) // Query - await assertQuerySuccess(modelType: PrivatePublicComboAPIPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicComboAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicComboAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicComboAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -128,9 +145,11 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { /// from syncing and DataStore getting to a “ready” state. func testOperationsForPrivatePublicComboAPIPost() async { let testId = UUID().uuidString - await setup(withModels: PrivatePublicComboModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePublicComboModels(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -139,14 +158,19 @@ class AWSDataStoreMultiAuthCombinationTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: PrivatePublicComboAPIPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicComboAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicComboAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicComboAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests+Models.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests+Models.swift index 32170dde44..ab0b7eb465 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests+Models.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests+Models.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Foundation import Combine +import Foundation +import XCTest @testable import Amplify diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests.swift index fc9264598c..4163e90aff 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthSingleRuleTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Foundation import Combine +import Foundation +import XCTest @testable import Amplify @@ -29,8 +29,10 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: OwnerUPPost.self, - expectations) { error in + await assertQuerySuccess( + modelType: OwnerUPPost.self, + expectations + ) { error in XCTFail("Error query \(error)") } @@ -68,14 +70,18 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: GroupUPPost.self, - expectations) { error in + await assertQuerySuccess( + modelType: GroupUPPost.self, + expectations + ) { error in XCTFail("Error query \(error)") } // Mutation - await assertMutations(model: GroupUPPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupUPPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -110,11 +116,12 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { await fulfillment(of: [authTypeExpecation], timeout: 5) await fulfillment(of: [ - expectations.query, - expectations.mutationSave, - expectations.mutationSaveProcessed, - expectations.mutationDelete, - expectations.mutationDeleteProcessed], timeout: TestCommonConstants.networkTimeout) + expectations.query, + expectations.mutationSave, + expectations.mutationSaveProcessed, + expectations.mutationDelete, + expectations.mutationDeleteProcessed + ], timeout: TestCommonConstants.networkTimeout) } @@ -139,14 +146,18 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) - await assertQuerySuccess(modelType: PrivateUPPost.self, - expectations) { error in + await assertQuerySuccess( + modelType: PrivateUPPost.self, + expectations + ) { error in XCTFail("Error query \(error)") } // Mutations - await assertMutations(model: PrivateUPPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivateUPPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -169,14 +180,19 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) - await assertQuerySuccess(modelType: PrivateIAMPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PrivateIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivateIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivateIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -198,14 +214,19 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PublicIAMPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PublicIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PublicIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PublicIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -227,14 +248,19 @@ class AWSDataStoreMultiAuthSingleRuleTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: PublicAPIPost.self, - expectations, onFailure: { error in + await assertQuerySuccess( + modelType: PublicAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PublicAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PublicAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthThreeRulesTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthThreeRulesTests.swift index 1ac6d4a481..861672c2d8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthThreeRulesTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthThreeRulesTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Combine +import Foundation import XCTest @testable import Amplify @@ -24,9 +24,11 @@ class AWSDataStoreMultiAuthThreeRulesTests: AWSDataStoreAuthBaseTest { /// fail with User Pool auth but succeed with IAM auth for an authenticated user. func testOwnerPrivatePublicUserPoolsIAMAPIKeyAuthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: OwnerPrivatePublicUserPoolsAPIKeyModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: OwnerPrivatePublicUserPoolsAPIKeyModels(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -36,15 +38,19 @@ class AWSDataStoreMultiAuthThreeRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: OwnerPrivatePublicUPIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPrivatePublicUPIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -57,9 +63,11 @@ class AWSDataStoreMultiAuthThreeRulesTests: AWSDataStoreAuthBaseTest { /// - DataStore is successfully initialized, sync/mutation/subscription network requests are sent with API Key func testOwnerPrivatePublicUserPoolsIAMAPIKeyUnauthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: OwnerPrivatePublicUserPoolsAPIKeyModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: OwnerPrivatePublicUserPoolsAPIKeyModels(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -68,15 +76,19 @@ class AWSDataStoreMultiAuthThreeRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: OwnerPrivatePublicUPIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPrivatePublicUPIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -94,9 +106,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// with Cognito auth for authenticated users func testGroupPrivatePublicUserPoolsIAMAPIKeyAuthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: GroupPrivatePublicUserPoolsAPIKeyModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: GroupPrivatePublicUserPoolsAPIKeyModels(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -106,15 +120,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: GroupPrivatePublicUPIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPrivatePublicUPIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -127,9 +145,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// - DataStore is successfully initialized, sync/mutation/subscription network requests are sent with API Key func testGroupPrivatePublicUserPoolsIAMAPIKeyUnauthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: GroupPrivatePublicUserPoolsAPIKeyModels(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: GroupPrivatePublicUserPoolsAPIKeyModels(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -138,14 +158,18 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: GroupPrivatePublicUPIAMAPIPost.self, - expectations) { error in + await assertQuerySuccess( + modelType: GroupPrivatePublicUPIAMAPIPost.self, + expectations + ) { error in XCTFail("Error query \(error)") } // Mutation - await assertMutations(model: GroupPrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -162,9 +186,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// with Cognito func testPrivatePrivatePublicUserPoolsIAMIAMAuthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePrivatePublicUserPoolsIAMIAM(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePrivatePublicUserPoolsIAMIAM(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -174,14 +200,18 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePrivatePublicUPIAMIAMPost.self, - expectations) { error in + await assertQuerySuccess( + modelType: PrivatePrivatePublicUPIAMIAMPost.self, + expectations + ) { error in XCTFail("Error query \(error)") } // Mutation - await assertMutations(model: PrivatePrivatePublicUPIAMIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePrivatePublicUPIAMIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -194,9 +224,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// - DataStore is successfully initialized, sync/mutation/subscription network requests are sent with IAM func testPrivatePrivatePublicUserPoolsIAMIAMUnauthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePrivatePublicUserPoolsIAMIAM(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePrivatePublicUserPoolsIAMIAM(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -205,15 +237,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PrivatePrivatePublicUPIAMIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePrivatePublicUPIAMIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePrivatePublicUPIAMIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePrivatePublicUPIAMIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -230,9 +266,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// with Cognito func testPrivatePrivatePublicUserPoolsIAMApiKeyAuthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePrivatePublicUserPoolsIAMAPiKey(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePrivatePublicUserPoolsIAMAPiKey(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -242,15 +280,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePrivatePublicUPIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePrivatePublicUPIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -265,9 +307,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// User Pool auth but succeed with IAM auth for an authenticated user. func testPrivatePrivatePublicUserPoolsIAMApiKeyUnauthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePrivatePublicUserPoolsIAMAPiKey(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePrivatePublicUserPoolsIAMAPiKey(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -276,15 +320,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: PrivatePrivatePublicUPIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePrivatePublicUPIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePrivatePublicUPIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePrivatePublicUPIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -301,9 +349,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// with Cognito func testPrivatePublicPublicUserPoolsAPIKeyIAMAuthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePublicPublicUserPoolsAPIKeyIAM(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePublicPublicUserPoolsAPIKeyIAM(), + testType: .multiAuth, + testId: testId + ) await signIn(user: user1) let expectations = makeExpectations() @@ -313,15 +363,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePublicPublicUPAPIIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicPublicUPAPIIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicPublicUPAPIIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicPublicUPAPIIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -336,9 +390,11 @@ extension AWSDataStoreMultiAuthThreeRulesTests { /// public IAM auth but succeed with API key auth. func testPrivatePublicPublicUserPoolsAPIKeyIAMUnauthenticatedUsers() async { let testId = UUID().uuidString - await setup(withModels: PrivatePublicPublicUserPoolsAPIKeyIAM(), - testType: .multiAuth, - testId: testId) + await setup( + withModels: PrivatePublicPublicUserPoolsAPIKeyIAM(), + testType: .multiAuth, + testId: testId + ) let expectations = makeExpectations() @@ -347,15 +403,19 @@ extension AWSDataStoreMultiAuthThreeRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PrivatePublicPublicUPAPIIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicPublicUPAPIIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutations - await assertMutations(model: PrivatePublicPublicUPAPIIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicPublicUPAPIIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests+Models.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests+Models.swift index b9bac33555..971cd9e2ac 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests+Models.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests+Models.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension AWSDataStoreMultiAuthTwoRulesTests { struct OwnerPrivateUserPoolsIAMModels: AmplifyModelRegistration { diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests.swift index 29e7979f38..97c1616418 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/AWSDataStoreMultiAuthTwoRulesTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation +import AWSAPIPlugin import Combine +import Foundation import XCTest -import AWSAPIPlugin @testable import Amplify @@ -30,15 +30,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { await assertDataStoreReady(expectations) let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) - await assertQuerySuccess(modelType: OwnerPrivateUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPrivateUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: model, - expectations) { error in + await assertMutations( + model: model, + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -63,15 +67,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: OwnerPublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -92,15 +100,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: OwnerPublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -125,15 +137,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: OwnerPublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } await fulfillment(of: [authTypeExpecation], timeout: 5) @@ -153,15 +169,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: OwnerPublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -205,15 +225,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: OwnerPublicOIDAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: OwnerPublicOIDAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: OwnerPublicOIDAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: OwnerPublicOIDAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -238,15 +262,19 @@ class AWSDataStoreMultiAuthTwoRulesTests: AWSDataStoreAuthBaseTest { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: GroupPrivateUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPrivateUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPrivateUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPrivateUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -272,15 +300,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: GroupPublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -301,15 +333,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: GroupPublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -335,15 +371,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: GroupPublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -364,15 +404,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: GroupPublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: GroupPublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: GroupPublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: GroupPublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -397,15 +441,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePrivateUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePrivateUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePrivateUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePrivateUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -431,15 +479,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -460,15 +512,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: PrivatePublicUPAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicUPAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicUPAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicUPAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -495,15 +551,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.amazonCognitoUserPools]) // Query - await assertQuerySuccess(modelType: PrivatePublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -524,15 +584,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PrivatePublicUPIAMPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicUPIAMPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicUPIAMPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicUPIAMPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -559,15 +623,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpecation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PrivatePublicIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -589,15 +657,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { await assertDataStoreReady(expectations) let authTypeExpectations = assertUsedAuthTypes(testId: testId, authTypes: [.apiKey]) // Query - await assertQuerySuccess(modelType: PrivatePublicIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PrivatePublicIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PrivatePublicIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PrivatePublicIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -621,15 +693,19 @@ extension AWSDataStoreMultiAuthTwoRulesTests { let authTypeExpectation = assertUsedAuthTypes(testId: testId, authTypes: [.awsIAM]) // Query - await assertQuerySuccess(modelType: PublicPublicIAMAPIPost.self, - expectations, - onFailure: { error in + await assertQuerySuccess( + modelType: PublicPublicIAMAPIPost.self, + expectations, + onFailure: { error in XCTFail("Error query \(error)") - }) + } + ) // Mutation - await assertMutations(model: PublicPublicIAMAPIPost(name: "name"), - expectations) { error in + await assertMutations( + model: PublicPublicIAMAPIPost(name: "name"), + expectations + ) { error in XCTFail("Error mutation \(error)") } @@ -642,11 +718,11 @@ extension AWSDataStoreMultiAuthTwoRulesTests { class TestAuthProviderFactory: APIAuthProviderFactory { class TestOIDCAuthProvider: AmplifyOIDCAuthProvider { - + func getLatestAuthToken() async throws -> String { throw DataStoreError.unknown("Not implemented", "Expected, we're testing unauthorized users.") } - + func getUserPoolAccessToken() async throws -> String { throw DataStoreError.unknown("Not implemented", "Expected, we're testing unauthorized users.") } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost+Schema.swift index 9c6dd62b10..dc834af993 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension GroupPrivatePublicUPIAMAPIPost { +public extension GroupPrivatePublicUPIAMAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let groupPrivatePublicUPIAMAPIPost = GroupPrivatePublicUPIAMAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost.swift index 7d4be15c66..bb0626f7b2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivatePublicUPIAMAPIPost.swift @@ -15,17 +15,23 @@ public struct GroupPrivatePublicUPIAMAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost+Schema.swift index c0ab2e2ec9..9ce386430e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension GroupPrivateUPIAMPost { +public extension GroupPrivateUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let groupPrivateUPIAMPost = GroupPrivateUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost.swift index ce3958ecc4..e30b70e1b9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPrivateUPIAMPost.swift @@ -15,17 +15,23 @@ public struct GroupPrivateUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost+Schema.swift index 16f97e6c85..5d125de36a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension GroupPublicUPAPIPost { +public extension GroupPublicUPAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let groupPublicUPAPIPost = GroupPublicUPAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost.swift index 3fb53d6f6f..adeacc180b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPAPIPost.swift @@ -15,17 +15,23 @@ public struct GroupPublicUPAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost+Schema.swift index 201e5f3b04..9552dd07c4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension GroupPublicUPIAMPost { +public extension GroupPublicUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let groupPublicUPIAMPost = GroupPublicUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost.swift index a7342cb275..24c83bd79e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupPublicUPIAMPost.swift @@ -15,17 +15,23 @@ public struct GroupPublicUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost+Schema.swift index fecc21dc17..b193f72c4f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension GroupUPPost { +public extension GroupUPPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let groupUPPost = GroupUPPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost.swift index 550fece3a5..0d6f9e0d85 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/GroupUPPost.swift @@ -15,17 +15,23 @@ public struct GroupUPPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost+Schema.swift index 216581701c..ad3e29ba99 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerOIDCPost { +public extension OwnerOIDCPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerOIDCPost = OwnerOIDCPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost.swift index 4840da2d1f..90b0a99de1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerOIDCPost.swift @@ -15,17 +15,23 @@ public struct OwnerOIDCPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost+Schema.swift index ab2ee1c581..9ba53e8530 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerPrivatePublicUPIAMAPIPost { +public extension OwnerPrivatePublicUPIAMAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerPrivatePublicUPIAMAPIPost = OwnerPrivatePublicUPIAMAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost.swift index e4ec5102df..3f1a5e0a30 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivatePublicUPIAMAPIPost.swift @@ -15,17 +15,23 @@ public struct OwnerPrivatePublicUPIAMAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost+Schema.swift index 9cb3394fa0..964a9c198f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerPrivateUPIAMPost { +public extension OwnerPrivateUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerPrivateUPIAMPost = OwnerPrivateUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost.swift index 0d97d19833..7afb326a25 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPrivateUPIAMPost.swift @@ -15,17 +15,23 @@ public struct OwnerPrivateUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost+Schema.swift index 9c92fdf569..3db935e968 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerPublicOIDAPIPost { +public extension OwnerPublicOIDAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerPublicOIDAPIPost = OwnerPublicOIDAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost.swift index 5f7ba8a80c..5ea950fffb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicOIDAPIPost.swift @@ -15,17 +15,23 @@ public struct OwnerPublicOIDAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost+Schema.swift index d631bee47b..4d7221f4fb 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerPublicUPAPIPost { +public extension OwnerPublicUPAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerPublicUPAPIPost = OwnerPublicUPAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost.swift index fc38cf0020..e3c8be119f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPAPIPost.swift @@ -15,17 +15,23 @@ public struct OwnerPublicUPAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost+Schema.swift index 52989229f2..6bf59cc538 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerPublicUPIAMPost { +public extension OwnerPublicUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerPublicUPIAMPost = OwnerPublicUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost.swift index 83534f1a61..530800fd2c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerPublicUPIAMPost.swift @@ -15,17 +15,23 @@ public struct OwnerPublicUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost+Schema.swift index dca06b5ae9..e8fe2536d3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension OwnerUPPost { +public extension OwnerUPPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let ownerUPPost = OwnerUPPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost.swift index 367434a454..f095fe95cf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/OwnerUPPost.swift @@ -15,17 +15,23 @@ public struct OwnerUPPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost+Schema.swift index 3e0a1da20e..a46fbcbb77 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivateIAMPost { +public extension PrivateIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privateIAMPost = PrivateIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost.swift index 479195fb93..fd80fd22d4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateIAMPost.swift @@ -15,17 +15,23 @@ public struct PrivateIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost+Schema.swift index ff4f34d012..12c20b2cfc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePrivatePublicUPIAMAPIPost { +public extension PrivatePrivatePublicUPIAMAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePrivatePublicUPIAMAPIPost = PrivatePrivatePublicUPIAMAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost.swift index 658b9d43c6..e63b3652e9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMAPIPost.swift @@ -15,17 +15,23 @@ public struct PrivatePrivatePublicUPIAMAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost+Schema.swift index 3523034148..07cc137671 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePrivatePublicUPIAMIAMPost { +public extension PrivatePrivatePublicUPIAMIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePrivatePublicUPIAMIAMPost = PrivatePrivatePublicUPIAMIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost.swift index 5ff60a442b..24e0b02774 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivatePublicUPIAMIAMPost.swift @@ -15,17 +15,23 @@ public struct PrivatePrivatePublicUPIAMIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost+Schema.swift index 900106d620..1699d1be57 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePrivateUPIAMPost { +public extension PrivatePrivateUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePrivateUPIAMPost = PrivatePrivateUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost.swift index c08743f094..fee351c261 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePrivateUPIAMPost.swift @@ -15,17 +15,23 @@ public struct PrivatePrivateUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost+Schema.swift index 4dabee89d7..334005238f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicComboAPIPost { +public extension PrivatePublicComboAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicComboAPIPost = PrivatePublicComboAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost.swift index 1328daac10..207a986053 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboAPIPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicComboAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost+Schema.swift index 0ede943be2..b62b24cad1 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicComboUPPost { +public extension PrivatePublicComboUPPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicComboUPPost = PrivatePublicComboUPPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost.swift index 2360d03013..30d0f3155c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicComboUPPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicComboUPPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost+Schema.swift index 6579e31a8f..e2d70b39fe 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicIAMAPIPost { +public extension PrivatePublicIAMAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicIAMAPIPost = PrivatePublicIAMAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost.swift index 5f88dd6717..8dbf482e12 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicIAMAPIPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicIAMAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost+Schema.swift index 414e3a7444..8aa139b622 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicPublicUPAPIIAMPost { +public extension PrivatePublicPublicUPAPIIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicPublicUPAPIIAMPost = PrivatePublicPublicUPAPIIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost.swift index 83f0d3a703..f2dcc38d1a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicPublicUPAPIIAMPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicPublicUPAPIIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost+Schema.swift index 592a83f6f6..0c62cf4dd7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicUPAPIPost { +public extension PrivatePublicUPAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicUPAPIPost = PrivatePublicUPAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost.swift index 8d1d35ba3d..72a2f40e67 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPAPIPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicUPAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost+Schema.swift index 0e160491aa..9c19e8f941 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivatePublicUPIAMPost { +public extension PrivatePublicUPIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privatePublicUPIAMPost = PrivatePublicUPIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost.swift index c902b2daf6..400d87d87b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivatePublicUPIAMPost.swift @@ -15,17 +15,23 @@ public struct PrivatePublicUPIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost+Schema.swift index 33606dc7c9..ee15a2eafc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PrivateUPPost { +public extension PrivateUPPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let privateUPPost = PrivateUPPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost.swift index d487bdedf5..e4c15445e4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PrivateUPPost.swift @@ -15,17 +15,23 @@ public struct PrivateUPPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost+Schema.swift index 6412e25a65..a49f4b29e9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PublicAPIPost { +public extension PublicAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let publicAPIPost = PublicAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost.swift index e5f10b107e..ef4dd44811 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicAPIPost.swift @@ -15,17 +15,23 @@ public struct PublicAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost+Schema.swift index d51b761442..054e275734 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PublicIAMPost { +public extension PublicIAMPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let publicIAMPost = PublicIAMPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost.swift index a6132c5ad2..5d1daea252 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicIAMPost.swift @@ -15,17 +15,23 @@ public struct PublicIAMPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost+Schema.swift index 9473b113d6..00d7f9dfaa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension PublicPublicIAMAPIPost { +public extension PublicPublicIAMAPIPost { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let publicPublicIAMAPIPost = PublicPublicIAMAPIPost.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost.swift index 58f3770c1b..8895229fc8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginMultiAuthTests/Models/PublicPublicIAMAPIPost.swift @@ -15,17 +15,23 @@ public struct PublicPublicIAMAPIPost: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2+Schema.swift index e51bfa5402..f798199559 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project1V2 { +public extension Project1V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project1V2 { case project1V2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project1V2 = Project1V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2.swift index 34440bbb51..7cf9f9a23f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Project1V2.swift @@ -17,23 +17,29 @@ public struct Project1V2: Model { public var updatedAt: Temporal.DateTime? public var project1V2TeamId: String? - public init(id: String = UUID().uuidString, - name: String? = nil, - team: Team1V2? = nil, - project1V2TeamId: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team1V2? = nil, + project1V2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project1V2TeamId: project1V2TeamId) + project1V2TeamId: project1V2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team1V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project1V2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team1V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project1V2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2+Schema.swift index 8ed0f54ddf..2fa869b077 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Team1V2 { +public extension Team1V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team1V2 = Team1V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2.swift index ed29653b08..9e547cc972 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/1V2/Team1V2.swift @@ -15,17 +15,23 @@ public struct Team1V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2+Schema.swift index 286ca57848..b1d25f76ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project2V2 { +public extension Project2V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case teamID @@ -20,10 +20,10 @@ extension Project2V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project2V2 = Project2V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2.swift index fed160bd8c..adc2cfc7fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Project2V2.swift @@ -17,23 +17,29 @@ public struct Project2V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2V2? = nil + ) { + self.init( + id: id, name: name, teamID: teamID, team: team, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - teamID: String, - team: Team2V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + teamID: String, + team: Team2V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.teamID = teamID diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2+Schema.swift index 43e0f11b00..0db2c5e78b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Team2V2 { +public extension Team2V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team2V2 = Team2V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2.swift index 7f13b3927a..9b8e27a8b3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/2V2/Team2V2.swift @@ -15,17 +15,23 @@ public struct Team2V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String + ) { + self.init( + id: id, name: name, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2+Schema.swift index cee3850f92..023f2e2d90 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment3V2 { +public extension Comment3V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case postID case content @@ -19,10 +19,10 @@ extension Comment3V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment3V2 = Comment3V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2.swift index 52f14a06fe..6f0647dd70 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Comment3V2.swift @@ -16,20 +16,26 @@ public struct Comment3V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - postID: String, - content: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + postID: String, + content: String + ) { + self.init( + id: id, postID: postID, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - postID: String, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + postID: String, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.postID = postID self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2+Schema.swift index f377adf509..e8525efd3a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post3V2 { +public extension Post3V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post3V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post3V2 = Post3V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2.swift index 365ff8bc83..bfd3f9db93 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3V2/Post3V2.swift @@ -16,20 +16,26 @@ public struct Post3V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift index 41081acbfc..a2efc3dd3f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment3aV2 { +public extension Comment3aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt @@ -19,10 +19,10 @@ extension Comment3aV2 { case post3aV2CommentsId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment3aV2 = Comment3aV2.keys model.pluralName = "Comment3aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2.swift index 883bbd6eb8..362732db79 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Comment3aV2.swift @@ -16,20 +16,26 @@ public struct Comment3aV2: Model { public var updatedAt: Temporal.DateTime? public var post3aV2CommentsId: String? - public init(id: String = UUID().uuidString, - content: String, - post3aV2CommentsId: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + post3aV2CommentsId: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, updatedAt: nil, - post3aV2CommentsId: post3aV2CommentsId) + post3aV2CommentsId: post3aV2CommentsId + ) } - internal init(id: String = UUID().uuidString, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - post3aV2CommentsId: String? = nil) { + init( + id: String = UUID().uuidString, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + post3aV2CommentsId: String? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift index 3b33c9960e..067713be06 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post3aV2 { +public extension Post3aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post3aV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post3aV2 = Post3aV2.keys model.pluralName = "Post3aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2.swift index 5332fcf81a..78361ec783 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/3aV2/Post3aV2.swift @@ -16,20 +16,26 @@ public struct Post3aV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2+Schema.swift index db568413b1..90683b5561 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment4V2 { +public extension Comment4V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment4V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment4V2 = Comment4V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2.swift index 5873d993e4..0d4073d6b4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Comment4V2.swift @@ -16,20 +16,26 @@ public struct Comment4V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String, - post: Post4V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String, + post: Post4V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2+Schema.swift index c0fa5fdfbb..e010e1c080 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post4V2 { +public extension Post4V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case comments @@ -19,10 +19,10 @@ extension Post4V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post4V2 = Post4V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2.swift index 7978edceb7..9106744759 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4V2/Post4V2.swift @@ -16,20 +16,26 @@ public struct Post4V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + comments: List? = [] + ) { + self.init( + id: id, title: title, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.comments = comments diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift index 5142fd05de..63cb47ada7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project4aV2 { +public extension Project4aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project4aV2 { case project4aV2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project4aV2 = Project4aV2.keys model.pluralName = "Project4aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2.swift index 51b873975c..4777b1dcda 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Project4aV2.swift @@ -21,23 +21,29 @@ public class Project4aV2: Model { public var updatedAt: Temporal.DateTime? public var project4aV2TeamId: String? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String? = nil, team: Team4aV2? = nil, - project4aV2TeamId: String? = nil) { - self.init(id: id, + project4aV2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project4aV2TeamId: project4aV2TeamId) + project4aV2TeamId: project4aV2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team4aV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project4aV2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team4aV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project4aV2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift index 9b7cae724e..18ccef180d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Team4aV2 { +public extension Team4aV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case project @@ -19,10 +19,10 @@ extension Team4aV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team4aV2 = Team4aV2.keys model.pluralName = "Team4aV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2.swift index 71d880f56b..7abfb7100b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4aV2/Team4aV2.swift @@ -16,20 +16,26 @@ public class Team4aV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String, - project: Project4aV2? = nil) { - self.init(id: id, + project: Project4aV2? = nil + ) { + self.init( + id: id, name: name, project: project, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - project: Project4aV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + project: Project4aV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.project = project diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift index 236d2be094..e3f4983c80 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Project4bV2 { +public extension Project4bV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case team @@ -20,10 +20,10 @@ extension Project4bV2 { case project4bV2TeamId } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let project4bV2 = Project4bV2.keys model.pluralName = "Project4bV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2.swift index 2369a6c57b..9b280c61df 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Project4bV2.swift @@ -17,23 +17,29 @@ public class Project4bV2: Model { public var updatedAt: Temporal.DateTime? public var project4bV2TeamId: String? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String? = nil, team: Team4bV2? = nil, - project4bV2TeamId: String? = nil) { - self.init(id: id, + project4bV2TeamId: String? = nil + ) { + self.init( + id: id, name: name, team: team, createdAt: nil, updatedAt: nil, - project4bV2TeamId: project4bV2TeamId) + project4bV2TeamId: project4bV2TeamId + ) } - internal init(id: String = UUID().uuidString, - name: String? = nil, - team: Team4bV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil, - project4bV2TeamId: String? = nil) { + init( + id: String = UUID().uuidString, + name: String? = nil, + team: Team4bV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil, + project4bV2TeamId: String? = nil + ) { self.id = id self.name = name self.team = team diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift index 311044fad2..eb0ec1c290 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Team4bV2 { +public extension Team4bV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case project @@ -19,10 +19,10 @@ extension Team4bV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let team4bV2 = Team4bV2.keys model.pluralName = "Team4bV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2.swift index 644c856c81..b1831b611b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/4bV2/Team4bV2.swift @@ -16,20 +16,26 @@ public class Team4bV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public convenience init(id: String = UUID().uuidString, + public convenience init( + id: String = UUID().uuidString, name: String, - project: Project4bV2? = nil) { - self.init(id: id, + project: Project4bV2? = nil + ) { + self.init( + id: id, name: name, project: project, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - project: Project4bV2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + project: Project4bV2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.project = project diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2+Schema.swift index 84a32e2cb8..9528d2576d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post5V2 { +public extension Post5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case editors @@ -19,10 +19,10 @@ extension Post5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post5V2 = Post5V2.keys model.pluralName = "Post5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2.swift index 3165ee7f99..1090df258b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/Post5V2.swift @@ -16,20 +16,26 @@ public struct Post5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - editors: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + editors: List? = [] + ) { + self.init( + id: id, title: title, editors: editors, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - editors: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + editors: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.editors = editors diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift index cdbcd3e07d..23a7be5848 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension PostEditor5V2 { +public extension PostEditor5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post5V2 case user5V2 @@ -19,10 +19,10 @@ extension PostEditor5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let postEditor5V2 = PostEditor5V2.keys model.pluralName = "PostEditor5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2.swift index f78bbe9420..dabb434aac 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/PostEditor5V2.swift @@ -16,20 +16,26 @@ public struct PostEditor5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - post5V2: Post5V2, - user5V2: User5V2) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + post5V2: Post5V2, + user5V2: User5V2 + ) { + self.init( + id: id, post5V2: post5V2, user5V2: user5V2, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - post5V2: Post5V2, - user5V2: User5V2, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + post5V2: Post5V2, + user5V2: User5V2, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.post5V2 = post5V2 self.user5V2 = user5V2 diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2+Schema.swift index 5c35bd5ad9..a15d33b3ab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension User5V2 { +public extension User5V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case username case posts @@ -19,10 +19,10 @@ extension User5V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let user5V2 = User5V2.keys model.pluralName = "User5V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2.swift index 7329a37803..dbf049a0f0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/5V2/User5V2.swift @@ -16,20 +16,26 @@ public struct User5V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - username: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + username: String, + posts: List? = [] + ) { + self.init( + id: id, username: username, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - username: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + username: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.username = username self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2+Schema.swift index 0c2d801a88..280cafde47 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog6V2 { +public extension Blog6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts @@ -19,10 +19,10 @@ extension Blog6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog6V2 = Blog6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2.swift index 1d1c62c34c..b4cbf30247 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Blog6V2.swift @@ -16,20 +16,26 @@ public struct Blog6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2+Schema.swift index 2d8fe7959c..cb476aa8cc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment6V2 { +public extension Comment6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case post case content @@ -19,10 +19,10 @@ extension Comment6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment6V2 = Comment6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2.swift index f975f70fb2..027da3fbc5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Comment6V2.swift @@ -16,20 +16,26 @@ public struct Comment6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - post: Post6V2? = nil, - content: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + post: Post6V2? = nil, + content: String + ) { + self.init( + id: id, post: post, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - post: Post6V2? = nil, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + post: Post6V2? = nil, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.post = post self.content = content diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2+Schema.swift index 5e96bf8cd9..8322b709e5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post6V2 { +public extension Post6V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case blog @@ -20,10 +20,10 @@ extension Post6V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post6V2 = Post6V2.keys model.authRules = [ diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2.swift index bebe11af46..c955a6e87e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/6V2/Post6V2.swift @@ -17,23 +17,29 @@ public struct Post6V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - blog: Blog6V2? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + blog: Blog6V2? = nil, + comments: List? = [] + ) { + self.init( + id: id, title: title, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - blog: Blog6V2? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + blog: Blog6V2? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.blog = blog diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2+Schema.swift index 84fa41ace3..5e2f6f64ca 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog7V2 { +public extension Blog7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case posts @@ -19,10 +19,10 @@ extension Blog7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog7V2 = Blog7V2.keys model.pluralName = "Blog7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2.swift index e963392ee5..537cd210a4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Blog7V2.swift @@ -16,20 +16,26 @@ public struct Blog7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + posts: List? = [] + ) { + self.init( + id: id, name: name, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.posts = posts diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2+Schema.swift index 0f71ceb037..077286678f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment7V2 { +public extension Comment7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment7V2 = Comment7V2.keys model.pluralName = "Comment7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2.swift index 317bef7b62..fa9b8c14ec 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Comment7V2.swift @@ -16,20 +16,26 @@ public struct Comment7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post7V2? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post7V2? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post7V2? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post7V2? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2+Schema.swift index e16552145c..18d5da8dc9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post7V2 { +public extension Post7V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case blog @@ -20,10 +20,10 @@ extension Post7V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post7V2 = Post7V2.keys model.pluralName = "Post7V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2.swift index a1cb3dfb84..e6fe9a9aab 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/7V2/Post7V2.swift @@ -17,23 +17,29 @@ public struct Post7V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - blog: Blog7V2? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + blog: Blog7V2? = nil, + comments: List? = [] + ) { + self.init( + id: id, title: title, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - blog: Blog7V2? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + blog: Blog7V2? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.blog = blog diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift index d77a61d5ee..aa10f9edd5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension Attendee8V2 { +public extension Attendee8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case meetings case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let attendee8V2 = Attendee8V2.keys model.pluralName = "Attendee8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2.swift index bdb90d7726..1ae9221f59 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Attendee8V2.swift @@ -15,17 +15,23 @@ public struct Attendee8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - meetings: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + meetings: List? = [] + ) { + self.init( + id: id, meetings: meetings, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - meetings: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + meetings: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.meetings = meetings self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift index ea734e16d1..540f9e81b7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Meeting8V2 { +public extension Meeting8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case title case attendees @@ -19,10 +19,10 @@ extension Meeting8V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let meeting8V2 = Meeting8V2.keys model.pluralName = "Meeting8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2.swift index 84abbbdd0c..8101985510 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Meeting8V2.swift @@ -16,20 +16,26 @@ public struct Meeting8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - title: String, - attendees: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + title: String, + attendees: List? = [] + ) { + self.init( + id: id, title: title, attendees: attendees, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - attendees: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + attendees: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.attendees = attendees diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2+Schema.swift index 72355ba4ea..303c84d91b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Registration8V2 { +public extension Registration8V2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case meeting case attendee @@ -19,10 +19,10 @@ extension Registration8V2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let registration8V2 = Registration8V2.keys model.pluralName = "Registration8V2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2.swift index f9d2aa3b4b..3c572b4969 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/8V2/Registration8V2.swift @@ -16,20 +16,26 @@ public struct Registration8V2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - meeting: Meeting8V2, - attendee: Attendee8V2) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + meeting: Meeting8V2, + attendee: Attendee8V2 + ) { + self.init( + id: id, meeting: meeting, attendee: attendee, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - meeting: Meeting8V2, - attendee: Attendee8V2, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + meeting: Meeting8V2, + attendee: Attendee8V2, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.meeting = meeting self.attendee = attendee diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift index f760ef2c9c..fae219e308 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerMultipleSecondaryIndexV2 { +public extension CustomerMultipleSecondaryIndexV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case phoneNumber @@ -21,10 +21,10 @@ extension CustomerMultipleSecondaryIndexV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerMultipleSecondaryIndexV2 = CustomerMultipleSecondaryIndexV2.keys model.pluralName = "CustomerMultipleSecondaryIndexV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift index 7e92f12052..1c4e60e2d5 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerMultipleSecondaryIndexV2.swift @@ -18,26 +18,32 @@ public struct CustomerMultipleSecondaryIndexV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - age: Int, - accountRepresentativeID: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + age: Int, + accountRepresentativeID: String + ) { + self.init( + id: id, name: name, phoneNumber: phoneNumber, age: age, accountRepresentativeID: accountRepresentativeID, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - age: Int, - accountRepresentativeID: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + age: Int, + accountRepresentativeID: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.phoneNumber = phoneNumber diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift index 3058f7d566..1118ef8ca6 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerSecondaryIndexV2 { +public extension CustomerSecondaryIndexV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case phoneNumber @@ -20,10 +20,10 @@ extension CustomerSecondaryIndexV2 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerSecondaryIndexV2 = CustomerSecondaryIndexV2.keys model.pluralName = "CustomerSecondaryIndexV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2.swift index e6e0d76c04..195405ac60 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerSecondaryIndexV2.swift @@ -17,23 +17,29 @@ public struct CustomerSecondaryIndexV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - accountRepresentativeID: String) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + accountRepresentativeID: String + ) { + self.init( + id: id, name: name, phoneNumber: phoneNumber, accountRepresentativeID: accountRepresentativeID, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - phoneNumber: String? = nil, - accountRepresentativeID: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + phoneNumber: String? = nil, + accountRepresentativeID: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.phoneNumber = phoneNumber diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift index 40e8c0f7ce..021d8bfa84 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension CustomerWithMultipleFieldsinPK { +public extension CustomerWithMultipleFieldsinPK { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case dob case date @@ -25,10 +25,10 @@ extension CustomerWithMultipleFieldsinPK { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let customerWithMultipleFieldsinPK = CustomerWithMultipleFieldsinPK.keys model.pluralName = "CustomerWithMultipleFieldsinPKs" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift index 32293d9975..0ae721e741 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/CustomerWithMultipleFieldsinPK.swift @@ -22,16 +22,19 @@ public struct CustomerWithMultipleFieldsinPK: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - date: Temporal.Date, - time: Temporal.Time, - phoneNumber: Int, - priority: Priority, - height: Double, - firstName: String? = nil, - lastName: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + date: Temporal.Date, + time: Temporal.Time, + phoneNumber: Int, + priority: Priority, + height: Double, + firstName: String? = nil, + lastName: String? = nil + ) { + self.init( + id: id, dob: dob, date: date, time: time, @@ -41,19 +44,22 @@ public struct CustomerWithMultipleFieldsinPK: Model { firstName: firstName, lastName: lastName, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - dob: Temporal.DateTime, - date: Temporal.Date, - time: Temporal.Time, - phoneNumber: Int, - priority: Priority, - height: Double, - firstName: String? = nil, - lastName: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + dob: Temporal.DateTime, + date: Temporal.Date, + time: Temporal.Time, + phoneNumber: Int, + priority: Priority, + height: Double, + firstName: String? = nil, + lastName: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.dob = dob self.date = date diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift index 03ace0efac..9f21d12e70 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Blog8 { +public extension Blog8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case customs @@ -21,10 +21,10 @@ extension Blog8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let blog8 = Blog8.keys model.pluralName = "Blog8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8.swift index 92c1ccae48..48aa59e7fc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Blog8.swift @@ -18,26 +18,32 @@ public struct Blog8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [] + ) { + self.init( + id: id, name: name, customs: customs, notes: notes, posts: posts, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - customs: [MyCustomModel8?]? = nil, - notes: [String?]? = nil, - posts: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + customs: [MyCustomModel8?]? = nil, + notes: [String?]? = nil, + posts: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.customs = customs diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift index 6258c76ca6..f2e773e8ee 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Comment8 { +public extension Comment8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case post @@ -19,10 +19,10 @@ extension Comment8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let comment8 = Comment8.keys model.pluralName = "Comment8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8.swift index 4a0042140e..d6fa843ba3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Comment8.swift @@ -16,20 +16,26 @@ public struct Comment8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8? = nil + ) { + self.init( + id: id, content: content, post: post, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - post: Post8? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + post: Post8? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.post = post diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift index 27f611af59..85693fb8fa 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyCustomModel8+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension MyCustomModel8 { +public extension MyCustomModel8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case desc case children } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let myCustomModel8 = MyCustomModel8.keys model.pluralName = "MyCustomModel8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift index 1d18ede96f..206fee3987 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/MyNestedModel8+Schema.swift @@ -9,18 +9,18 @@ import Amplify import Foundation -extension MyNestedModel8 { +public extension MyNestedModel8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case nestedName case notes } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let myNestedModel8 = MyNestedModel8.keys model.pluralName = "MyNestedModel8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift index bd21917eb4..5cf1fb9e29 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post8 { +public extension Post8 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case name case randomId @@ -21,10 +21,10 @@ extension Post8 { case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let post8 = Post8.keys model.pluralName = "Post8s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8.swift index 306eb3395b..09bec3b160 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/OptionalAssociations/Post8.swift @@ -18,26 +18,32 @@ public struct Post8: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8? = nil, - comments: List? = []) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8? = nil, + comments: List? = [] + ) { + self.init( + id: id, name: name, randomId: randomId, blog: blog, comments: comments, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - name: String, - randomId: String? = nil, - blog: Blog8? = nil, - comments: List? = [], - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + name: String, + randomId: String? = nil, + blog: Blog8? = nil, + comments: List? = [], + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.name = name self.randomId = randomId diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift index 5d527c5bdf..59af4deb74 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension SchemaDrift { +public extension SchemaDrift { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case enumValue case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let schemaDrift = SchemaDrift.keys model.pluralName = "SchemaDrifts" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift index dfac48fda6..b6159e7589 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/SchemaDrift/SchemaDrift.swift @@ -30,17 +30,23 @@ public struct SchemaDrift: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - enumValue: EnumDrift? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + enumValue: EnumDrift? = nil + ) { + self.init( + id: id, enumValue: enumValue, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - enumValue: EnumDrift? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + enumValue: EnumDrift? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.enumValue = enumValue self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift index 716f4848fe..2ed40a52b9 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension TodoCustomTimestampV2 { +public extension TodoCustomTimestampV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdOn case updatedOn } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoCustomTimestampV2 = TodoCustomTimestampV2.keys model.pluralName = "TodoCustomTimestampV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2.swift index 4bad844e17..97842a31a0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoCustomTimestampV2.swift @@ -15,17 +15,23 @@ public struct TodoCustomTimestampV2: Model { public var createdOn: Temporal.DateTime? public var updatedOn: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdOn: nil, - updatedOn: nil) + updatedOn: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdOn: Temporal.DateTime? = nil, - updatedOn: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdOn: Temporal.DateTime? = nil, + updatedOn: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdOn = createdOn diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift index 6de5d45ae2..0e390adf51 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2+Schema.swift @@ -9,19 +9,19 @@ import Amplify import Foundation -extension TodoWithDefaultValueV2 { +public extension TodoWithDefaultValueV2 { // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { + enum CodingKeys: String, ModelKey { case id case content case createdAt case updatedAt } - public static let keys = CodingKeys.self + static let keys = CodingKeys.self // MARK: - ModelSchema - public static let schema = defineSchema { model in + static let schema = defineSchema { model in let todoWithDefaultValueV2 = TodoWithDefaultValueV2.keys model.pluralName = "TodoWithDefaultValueV2s" diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2.swift index dd622e15fc..75c66e59c2 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/Models/TransformerV2/TodoWithDefaultValueV2.swift @@ -15,17 +15,23 @@ public struct TodoWithDefaultValueV2: Model { public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - public init(id: String = UUID().uuidString, - content: String? = nil) { - self.init(id: id, + public init( + id: String = UUID().uuidString, + content: String? = nil + ) { + self.init( + id: id, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - content: String? = nil, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + content: String? = nil, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.content = content self.createdAt = createdAt diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreInternal.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreInternal.swift index 84e7fb7f9b..beae3433c0 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreInternal.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreInternal.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import Foundation @testable import Amplify @testable import AWSDataStorePlugin -import Foundation -struct DataStoreInternal { +enum DataStoreInternal { static var dbFilePath: URL? { getAdapter()?.dbFilePath } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreTestBase.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreTestBase.swift index 35e47870b0..cfe22f662d 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/DataStoreTestBase.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import XCTest -import Amplify class DataStoreTestBase: XCTestCase { func saveModel(_ model: M) async throws -> M { @@ -18,7 +18,7 @@ class DataStoreTestBase: XCTestCase { return try await Amplify.DataStore.query(modelType, byId: id) } - func deleteModel(_ model: M) async throws { + func deleteModel(_ model: some Model) async throws { try await Amplify.DataStore.delete(model) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/SyncEngineIntegrationV2TestBase.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/SyncEngineIntegrationV2TestBase.swift index 7ff6649ed0..14dae15b13 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/SyncEngineIntegrationV2TestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TestSupport/SyncEngineIntegrationV2TestBase.swift @@ -54,11 +54,15 @@ class SyncEngineIntegrationV2TestBase: DataStoreTestBase { sessionFactory: AmplifyURLSessionFactory() )) #if os(watchOS) - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: .custom(syncMaxRecords: 100, disableSubscriptions: { false }))) + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: .custom(syncMaxRecords: 100, disableSubscriptions: { false }) + )) #else - try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, - configuration: .custom(syncMaxRecords: 100))) + try Amplify.add(plugin: AWSDataStorePlugin( + modelRegistration: models, + configuration: .custom(syncMaxRecords: 100) + )) #endif } catch { XCTFail(String(describing: error)) @@ -99,8 +103,10 @@ class SyncEngineIntegrationV2TestBase: DataStoreTestBase { let eventReceived = expectation(description: "DataStore \(eventName) event") var token: UnsubscribeToken! - token = Amplify.Hub.listen(to: .dataStore, - eventName: eventName) { _ in + token = Amplify.Hub.listen( + to: .dataStore, + eventName: eventName + ) { _ in eventReceived.fulfill() Amplify.Hub.removeListener(token) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionOptionalAssociations.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionOptionalAssociations.swift index 86c9fdc040..47855ad01f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionOptionalAssociations.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionOptionalAssociations.swift @@ -205,7 +205,7 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { XCTAssertEqual(queriedComment.post?.blog?.id, blog.id) XCTAssertNotNil(queriedPost.blog) XCTAssertEqual(queriedPost.blog?.id, blog.id) - + queriedComment.post = nil // A mock GraphQL request is created to assert that the request variables contains the "postId" // with the value `nil` which is sent to the API to persist the removal of the association. @@ -217,7 +217,7 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { XCTFail("Failed to retrieve input object from GraphQL variables") return } - + guard try await saveComment(queriedComment) != nil else { XCTFail("Failed to update comment") return @@ -226,15 +226,15 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { XCTFail("Failed to query comment without post") return } - + XCTAssertNil(queriedCommentWithoutPost.post) - + queriedPost.blog = nil guard try await savePost(queriedPost) != nil else { XCTFail("Failed to update post") return } - + guard let queriedPostWithoutBlog = try await queryPost(id: post.id) else { XCTFail("Failed to query post") return @@ -251,7 +251,7 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { func saveComment(_ comment: Comment8? = nil, withPost post: Post8? = nil) async throws -> Comment8? { let commentToSave: Comment8 - if let comment = comment { + if let comment { commentToSave = comment } else { commentToSave = Comment8(content: "content", post: post) @@ -279,7 +279,7 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { func savePost(_ post: Post8? = nil, withBlog blog: Blog8? = nil) async throws -> Post8? { let postToSave: Post8 - if let post = post { + if let post { postToSave = post } else { postToSave = Post8(name: "name", randomId: "randomId", blog: blog) @@ -307,16 +307,20 @@ class DataStoreConnectionOptionalAssociations: SyncEngineIntegrationV2TestBase { func saveBlog(_ blog: Blog8? = nil) async throws -> Blog8? { let blogToSave: Blog8 - if let blog = blog { + if let blog { blogToSave = blog } else { - let nestedModel = MyNestedModel8(id: UUID().uuidString, - nestedName: "nestedName", - notes: ["notes1", "notes2"]) - let customModel = MyCustomModel8(id: UUID().uuidString, - name: "name", - desc: "desc", - children: [nestedModel]) + let nestedModel = MyNestedModel8( + id: UUID().uuidString, + nestedName: "nestedName", + notes: ["notes1", "notes2"] + ) + let customModel = MyCustomModel8( + id: UUID().uuidString, + name: "name", + desc: "desc", + children: [nestedModel] + ) blogToSave = Blog8(name: "name", customs: [customModel], notes: ["notes1", "notes2"]) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario1V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario1V2Tests.swift index 4bdfa9c164..0ab86a8ab8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario1V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario1V2Tests.swift @@ -47,10 +47,12 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { let team = Team1V2(name: "name1") // TODO: No need to add the `team` into the project, it is using explicit field `project1V2TeamId` let project = Project1V2(team: team, project1V2TeamId: team.id) - + let syncedTeamReceived = expectation(description: "received team from sync path") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -68,10 +70,12 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { _ = try await Amplify.DataStore.save(team) await fulfillment(of: [syncedTeamReceived], timeout: TestCommonConstants.networkTimeout) - + let syncProjectReceived = expectation(description: "received project from sync path") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -84,12 +88,12 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { syncProjectReceived.fulfill() } } - + guard try await HubListenerTestUtilities.waitForListener(with: hubListener, timeout: 5.0) else { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(project) await fulfillment(of: [syncProjectReceived], timeout: TestCommonConstants.networkTimeout) @@ -109,18 +113,22 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { let anotherTeam = Team1V2(name: "name1") // TODO: No need to add the `team` into the project, it is using explicit field `project1V2TeamId` var project = Project1V2(team: team, project1V2TeamId: team.id) - let expectedUpdatedProject = Project1V2(id: project.id, - name: project.name, - team: anotherTeam, // Not needed - project1V2TeamId: anotherTeam.id) - + let expectedUpdatedProject = Project1V2( + id: project.id, + name: project.name, + team: anotherTeam, // Not needed + project1V2TeamId: anotherTeam.id + ) + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(anotherTeam) _ = try await Amplify.DataStore.save(project) - + let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -156,14 +164,16 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { func testCreateUpdateDeleteAndGetProjectReturnsNil() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team1V2(name: "name") var project = Project1V2(team: team, project1V2TeamId: team.id) let createReceived = expectation(description: "received created items from cloud") createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -192,8 +202,10 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let updateReceived = expectation(description: "received update project from sync path") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -211,15 +223,17 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + project.name = "updatedName" _ = try await Amplify.DataStore.save(project) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "Delete notification received") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -242,7 +256,7 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { return } _ = try await Amplify.DataStore.delete(project) - + // TODO: Delete Team should not be necessary, cascade delete should delete the team when deleting the project. // Once cascade works for hasOne, the following code can be removed. _ = try await Amplify.DataStore.delete(team) @@ -260,11 +274,13 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { let team = Team1V2(name: "name") let project = Project1V2(team: team, project1V2TeamId: team.id) - + let createReceived = expectation(description: "received created items from cloud") createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -288,16 +304,18 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "Delete notification received") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -335,14 +353,14 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { func testDeleteWithValidCondition() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team1V2(name: "name") let project = Project1V2(team: team, project1V2TeamId: team.id) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + _ = try await Amplify.DataStore.delete(project, where: Project1V2.keys.team.eq(team.id)) - + let queriedProject = try await Amplify.DataStore.query(Project1V2.self, byId: project.id) XCTAssertNil(queriedProject) } @@ -350,7 +368,7 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { func testDeleteWithInvalidCondition() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team1V2(name: "name") let project = Project1V2(team: team, project1V2TeamId: team.id) _ = try await Amplify.DataStore.save(team) @@ -379,7 +397,7 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { let project = Project1V2(team: team, project1V2TeamId: team.id) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + let predicate = Project1V2.keys.team.eq(team.id) let projects = try await Amplify.DataStore.query(Project1V2.self, where: predicate) XCTAssertEqual(projects.count, 1) @@ -389,8 +407,10 @@ class DataStoreConnectionScenario1V2Tests: SyncEngineIntegrationV2TestBase { } extension Team1V2: Equatable { - public static func == (lhs: Team1V2, - rhs: Team1V2) -> Bool { + public static func == ( + lhs: Team1V2, + rhs: Team1V2 + ) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario2V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario2V2Tests.swift index 5c30589420..12b8d98210 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario2V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario2V2Tests.swift @@ -49,9 +49,11 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { let team = Team2V2(name: "name1") let project = Project2V2(teamID: team.id, team: team) let syncedTeamReceived = expectation(description: "received team from sync event") - - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -66,13 +68,15 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(team) await fulfillment(of: [syncedTeamReceived], timeout: TestCommonConstants.networkTimeout) - + let syncProjectReceived = expectation(description: "received project from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -84,7 +88,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { syncProjectReceived.fulfill() } } - + _ = try await Amplify.DataStore.save(project) await fulfillment(of: [syncProjectReceived], timeout: TestCommonConstants.networkTimeout) @@ -103,14 +107,16 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { let anotherTeam = Team2V2(name: "name1") var project = Project2V2(teamID: team.id, team: team) let expectedUpdatedProject = Project2V2(id: project.id, name: project.name, teamID: anotherTeam.id) - + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(anotherTeam) _ = try await Amplify.DataStore.save(project) - + let syncUpdatedProjectReceived = expectation(description: "received updated project from sync path") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -121,7 +127,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { syncUpdatedProjectReceived.fulfill() } } - + guard try await HubListenerTestUtilities.waitForListener(with: hubListener, timeout: 5.0) else { XCTFail("Listener not registered for hub") return @@ -143,14 +149,16 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { func testCreateUpdateDeleteAndGetProjectReturnsNil() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team2V2(name: "name") var project = Project2V2(teamID: team.id, team: team) - + let createReceived = expectation(description: "received created items from cloud") createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -169,7 +177,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { } } } - + guard try await HubListenerTestUtilities.waitForListener(with: hubListener, timeout: 5.0) else { XCTFail("Listener not registered for hub") return @@ -178,10 +186,12 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let updateReceived = expectation(description: "received update project from sync path") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -199,15 +209,17 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + project.name = "updatedName" _ = try await Amplify.DataStore.save(project) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "received deleted project from sync path") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -234,7 +246,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { // Once cascade works for hasOne, the following code can be removed. _ = try await Amplify.DataStore.delete(team) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) - + let queriedProject = try await Amplify.DataStore.query(Project2V2.self, byId: project.id) XCTAssertNil(queriedProject) @@ -248,12 +260,14 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { let team = Team2V2(name: "name") let project = Project2V2(teamID: team.id, team: team) - + let createReceived = expectation(description: "received created items from cloud") createReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -276,16 +290,18 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "Delete notification received") deleteReceived.expectedFulfillmentCount = 2 // 1 project and 1 team - - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -326,12 +342,12 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { let team = Team2V2(name: "name") let project = Project2V2(teamID: team.id, team: team) - + _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + _ = try await Amplify.DataStore.delete(project, where: Project2V2.keys.team.eq(team.id)) - + let queriedProject = try await Amplify.DataStore.query(Project2V2.self, byId: project.id) XCTAssertNil(queriedProject) } @@ -339,12 +355,12 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { func testDeleteWithInvalidCondition() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team2V2(name: "name") let project = Project2V2(teamID: team.id, team: team) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + do { _ = try await Amplify.DataStore.delete(project, where: Project2V2.keys.teamID.eq("invalidTeamId")) XCTFail("Should have failed") @@ -356,7 +372,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { } catch { throw error } - + let queriedProject = try await Amplify.DataStore.query(Project2V2.self, byId: project.id) XCTAssertNotNil(queriedProject) } @@ -364,15 +380,15 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { func testDeleteAlreadyDeletedItemWithCondition() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let team = Team2V2(name: "name") let project = Project2V2(teamID: team.id, team: team) - + _ = try await Amplify.DataStore.delete(project) - + let queriedProjectOptional = try await Amplify.DataStore.query(Project2V2.self, byId: project.id) XCTAssertNil(queriedProjectOptional) - + _ = try await Amplify.DataStore.delete(project, where: Project2V2.keys.teamID == team.id) } @@ -384,7 +400,7 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { let project = Project2V2(teamID: team.id, team: team) _ = try await Amplify.DataStore.save(team) _ = try await Amplify.DataStore.save(project) - + let predicate = Project2V2.keys.teamID.eq(team.id) let projects = try await Amplify.DataStore.query(Project2V2.self, where: predicate) XCTAssertEqual(projects.count, 1) @@ -394,8 +410,10 @@ class DataStoreConnectionScenario2V2Tests: SyncEngineIntegrationV2TestBase { } extension Team2V2: Equatable { - public static func == (lhs: Team2V2, - rhs: Team2V2) -> Bool { + public static func == ( + lhs: Team2V2, + rhs: Team2V2 + ) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3V2Tests.swift index 2ca3fa52a2..e82fc6d841 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3V2Tests.swift @@ -48,8 +48,10 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let comment = Comment3V2(postID: post.id, content: "content") let syncedPostReceived = expectation(description: "received post from sync event") let syncCommentReceived = expectation(description: "received comment from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -67,11 +69,11 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) await fulfillment(of: [syncedPostReceived, syncCommentReceived], timeout: TestCommonConstants.networkTimeout) - + let queriedComment = try await Amplify.DataStore.query(Comment3V2.self, byId: comment.id) XCTAssertEqual(queriedComment, comment) } @@ -84,7 +86,7 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let comment = Comment3V2(postID: post.id, content: "content") _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + let queriedPostOptional = try await Amplify.DataStore.query(Post3V2.self, byId: post.id) guard let queriedPost = queriedPostOptional else { XCTFail("Could not get post") @@ -123,9 +125,9 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let comment = Comment3V2(postID: post.id, content: "content") _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + _ = try await Amplify.DataStore.delete(comment) - + let queriedComment = try await Amplify.DataStore.query(Comment3V2.self, byId: comment.id) XCTAssertNil(queriedComment) } @@ -138,7 +140,7 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let comment = Comment3V2(postID: post.id, content: "content") _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + let predicate = Comment3V2.keys.postID.eq(post.id) let queriedComments = try await Amplify.DataStore.query(Comment3V2.self, where: predicate) XCTAssertEqual(queriedComments.count, 1) @@ -151,8 +153,10 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let post = Post3V2(title: "title") let createReceived = expectation(description: "received post from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -180,8 +184,10 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { var post = Post3V2(title: "title") let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -201,12 +207,14 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { } _ = try await Amplify.DataStore.save(post) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let updatedTitle = "updatedTitle" post.title = updatedTitle let updateReceived = expectation(description: "received updated post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -230,10 +238,12 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() let post = Post3V2(title: "title") - + let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -255,8 +265,10 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let deleteReceived = expectation(description: "received deleted post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -274,7 +286,7 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.delete(post) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) } @@ -285,11 +297,13 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let post = Post3V2(title: "title") let comment = Comment3V2(postID: post.id, content: "content") - + let createReceived = expectation(description: "received created from sync event") createReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -319,8 +333,10 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "received deleted from sync event") deleteReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -340,7 +356,7 @@ class DataStoreConnectionScenario3V2Tests: SyncEngineIntegrationV2TestBase { } } } - + _ = try await Amplify.DataStore.delete(post) // TODO: Deleting the comment should not be necessary. Cascade delete is not working _ = try await Amplify.DataStore.delete(comment) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3aV2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3aV2Tests.swift index 18fae1693e..bb56879cb8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3aV2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario3aV2Tests.swift @@ -47,8 +47,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) let syncedPostReceived = expectation(description: "received post from sync event") let syncCommentReceived = expectation(description: "received comment from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -66,12 +68,12 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + await fulfillment(of: [syncedPostReceived, syncCommentReceived], timeout: TestCommonConstants.networkTimeout) - + let queriedComment = try await Amplify.DataStore.query(Comment3aV2.self, byId: comment.id) XCTAssertEqual(queriedComment, comment) } @@ -82,22 +84,22 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let post = Post3aV2(title: "title") let comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + let queriedPostOptional = try await Amplify.DataStore.query(Post3aV2.self, byId: post.id) guard let queriedPost = queriedPostOptional else { XCTFail("Could not get post") return } XCTAssertEqual(queriedPost.id, post.id) - + guard let comments = queriedPost.comments else { XCTFail("Could not get comments") return } - + try await comments.fetch() XCTAssertEqual(comments.count, 1) XCTAssertEqual(comments[0], comment) @@ -110,11 +112,11 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let post = Post3aV2(title: "title") var comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) let anotherPost = Post3aV2(title: "title") - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) _ = try await Amplify.DataStore.save(anotherPost) - + comment.post3aV2CommentsId = anotherPost.id let updatedComment = try await Amplify.DataStore.save(comment) XCTAssertEqual(updatedComment.post3aV2CommentsId, anotherPost.id) @@ -123,15 +125,15 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { func testDeleteAndGetComment() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post3aV2(title: "title") let comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + _ = try await Amplify.DataStore.delete(comment) - + let queriedComment = try await Amplify.DataStore.query(Comment3aV2.self, byId: comment.id) XCTAssertNil(queriedComment) } @@ -142,10 +144,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let post = Post3aV2(title: "title") let comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + let predicate = Comment3aV2.keys.post3aV2CommentsId.eq(post.id) let queriedComments = try await Amplify.DataStore.query(Comment3aV2.self, where: predicate) XCTAssertEqual(queriedComments.count, 1) @@ -158,8 +160,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let post = Post3aV2(title: "title") let createReceived = expectation(description: "received post from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -174,7 +178,7 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(post) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) @@ -188,8 +192,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { var post = Post3aV2(title: "title") let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -207,19 +213,21 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.save(post) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let updateReceived = expectation(description: "received updated post from sync event") let updatedTitle = "updatedTitle" - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return } - + if let syncedPost = try? mutationEvent.decodeModel() as? Post3aV2, syncedPost == post { if mutationEvent.mutationType == GraphQLMutationType.update.rawValue { @@ -229,12 +237,12 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { } } } - + guard try await HubListenerTestUtilities.waitForListener(with: hubListener, timeout: 5.0) else { XCTFail("Listener not registered for hub") return } - + post.title = updatedTitle _ = try await Amplify.DataStore.save(post) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) @@ -245,10 +253,12 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() let post = Post3aV2(title: "title") - + let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -270,8 +280,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let deleteReceived = expectation(description: "received deleted post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -290,11 +302,11 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.delete(post) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) } - + func testDeletePostCascadeToComments() async throws { await setUp(withModels: TestModelRegistration()) @@ -302,11 +314,13 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let post = Post3aV2(title: "title") let comment = Comment3aV2(content: "content", post3aV2CommentsId: post.id) - + let createReceived = expectation(description: "received created from sync event") createReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -336,8 +350,10 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "received deleted from sync event") deleteReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -361,7 +377,7 @@ class DataStoreConnectionScenario3aV2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.delete(post) // TODO: Deleting the comment should not be necessary. Cascade delete is not working _ = try await Amplify.DataStore.delete(comment) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario4V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario4V2Tests.swift index 0b2c2e9714..eeadeb9498 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario4V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario4V2Tests.swift @@ -63,7 +63,7 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { func testCreateCommentAndGetPostWithComments() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post4V2(title: "title") let comment = Comment4V2(content: "content", post: post) @@ -76,7 +76,7 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { return } XCTAssertEqual(queriedPost.id, post.id) - + guard let queriedComments = queriedPost.comments else { XCTFail("Could not get comments") return @@ -89,15 +89,15 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { func testUpdateComment() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post4V2(title: "title") var comment = Comment4V2(content: "content", post: post) let anotherPost = Post4V2(title: "title") - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) _ = try await Amplify.DataStore.save(anotherPost) - + comment.post = anotherPost let updatedComment = try await Amplify.DataStore.save(comment) XCTAssertEqual(updatedComment.post, anotherPost) @@ -106,10 +106,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { func testDeleteAndGetComment() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post4V2(title: "title") let comment = Comment4V2(content: "content", post: post) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) @@ -121,13 +121,13 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { func testListCommentsByPostID() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post4V2(title: "title") let comment = Comment4V2(content: "content", post: post) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(comment) - + let predicate = Comment4V2.keys.post.eq(post.id) let comments = try await Amplify.DataStore.query(Comment4V2.self, where: predicate) XCTAssertEqual(comments.count, 1) @@ -140,8 +140,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { let post = Post4V2(title: "title") let createReceived = expectation(description: "received post from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -152,7 +154,7 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { createReceived.fulfill() } } - + guard try await HubListenerTestUtilities.waitForListener(with: hubListener, timeout: 5.0) else { XCTFail("Listener not registered for hub") return @@ -170,8 +172,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { var post = Post4V2(title: "title") let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -194,8 +198,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { let updatedTitle = "updatedTitle" let updateReceived = expectation(description: "received updated post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -214,7 +220,7 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + post.title = updatedTitle _ = try await Amplify.DataStore.save(post) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) @@ -225,10 +231,12 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() let post = Post4V2(title: "title") - + let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -250,8 +258,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let deleteReceived = expectation(description: "received deleted post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -280,11 +290,13 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { let post = Post4V2(title: "title") let comment = Comment4V2(content: "content", post: post) - + let createReceived = expectation(description: "received created from sync event") createReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -314,8 +326,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "received deleted from sync event") deleteReceived.expectedFulfillmentCount = 2 // 1 post and 1 comment - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -345,8 +359,10 @@ class DataStoreConnectionScenario4V2Tests: SyncEngineIntegrationV2TestBase { } extension Post4V2: Equatable { - public static func == (lhs: Post4V2, - rhs: Post4V2) -> Bool { + public static func == ( + lhs: Post4V2, + rhs: Post4V2 + ) -> Bool { return lhs.id == rhs.id && lhs.title == rhs.title } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario5V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario5V2Tests.swift index 6cafde9e9a..673b3d8902 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario5V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario5V2Tests.swift @@ -45,15 +45,15 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { func testListPostEditorByPost() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + let post = Post5V2(title: "title") let user = User5V2(username: "username") let postEditor = PostEditor5V2(post5V2: post, user5V2: user) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(user) _ = try await Amplify.DataStore.save(postEditor) - + let predicateByPostId = PostEditor5V2.keys.post5V2.eq(post.id) let queriedPostEditor = try await Amplify.DataStore.query(PostEditor5V2.self, where: predicateByPostId) XCTAssertNotNil(queriedPostEditor) @@ -65,11 +65,11 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let post = Post5V2(title: "title") let user = User5V2(username: "username") let postEditor = PostEditor5V2(post5V2: post, user5V2: user) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(user) _ = try await Amplify.DataStore.save(postEditor) - + let predicateByUserId = PostEditor5V2.keys.user5V2.eq(user.id) let queriedPostEditor = try await Amplify.DataStore.query(PostEditor5V2.self, where: predicateByUserId) XCTAssertNotNil(queriedPostEditor) @@ -81,18 +81,18 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let post = Post5V2(title: "title") let user = User5V2(username: "username") let postEditor = PostEditor5V2(post5V2: post, user5V2: user) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(user) _ = try await Amplify.DataStore.save(postEditor) - + let queriedPostOptional = try await Amplify.DataStore.query(Post5V2.self, byId: post.id) guard let queriedPost = queriedPostOptional else { XCTFail("Missing queried post") return } XCTAssertEqual(queriedPost.id, post.id) - + guard let editors = queriedPost.editors else { XCTFail("Missing editors") return @@ -107,11 +107,11 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let post = Post5V2(title: "title") let user = User5V2(username: "username") let postEditor = PostEditor5V2(post5V2: post, user5V2: user) - + _ = try await Amplify.DataStore.save(post) _ = try await Amplify.DataStore.save(user) _ = try await Amplify.DataStore.save(postEditor) - + let queriedUserOptional = try await Amplify.DataStore.query(User5V2.self, byId: user.id) guard let queriedUser = queriedUserOptional else { XCTFail("Missing queried user") @@ -132,8 +132,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let post = Post5V2(title: "title") let createReceived = expectation(description: "received post from sync event") - let hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + let hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -161,8 +163,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { var post = Post5V2(title: "title") let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -186,8 +190,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let updateReceived = expectation(description: "received updated post from sync event") let updatedTitle = "updatedTitle" post.title = updatedTitle - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -202,7 +208,7 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { } } } - + _ = try await Amplify.DataStore.save(post) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) } @@ -213,8 +219,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let post = Post5V2(title: "title") let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -236,8 +244,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) let deleteReceived = expectation(description: "received deleted post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -270,8 +280,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let createReceived = expectation(description: "received created from sync event") createReceived.expectedFulfillmentCount = 3 // 1 post, 1 user, 1 postEditor - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -308,8 +320,10 @@ class DataStoreConnectionScenario5V2Tests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "received deleted from sync event") deleteReceived.expectedFulfillmentCount = 2 // 1 post, 1 postEditor - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario6V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario6V2Tests.swift index 6fd35b638c..8ffb6b6a85 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario6V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario6V2Tests.swift @@ -58,7 +58,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { let post1 = await savePost(title: "title", blog: blog), let _ = await savePost(title: "title", blog: blog), let comment1post1 = await saveComment(post: post1, content: "content"), - let comment2post1 = await saveComment(post: post1, content: "content") else { + let comment2post1 = await saveComment(post: post1, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } @@ -70,27 +71,27 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { } XCTAssertEqual(queriedBlog.id, blog.id) resultPosts = queriedBlog.posts - + guard let posts = resultPosts else { XCTFail("Could not get posts") return } - + try await posts.fetch() XCTAssertEqual(posts.count, 2) - guard let fetchedPost = posts.first(where: { (post) -> Bool in + guard let fetchedPost = posts.first(where: { post -> Bool in post.id == post1.id }), let comments = fetchedPost.comments else { XCTFail("Could not set up - failed to get a post and its comments") return } - + try await comments.fetch() XCTAssertEqual(comments.count, 2) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment1post1.id })) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment2post1.id })) if let post = comments[0].post { @@ -104,7 +105,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, post, and comment") return } @@ -138,11 +140,12 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, post, and comment") return } - + let queriedPostOptional = try await Amplify.DataStore.query(Post6V2.self, byId: post.id) guard let queriedPost = queriedPostOptional else { XCTFail("Could not get post") @@ -160,7 +163,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { if let postsInEagerlyLoadedBlog = eagerlyLoadedBlog.posts { try await postsInEagerlyLoadedBlog.fetch() XCTAssertEqual(postsInEagerlyLoadedBlog.count, 1) - XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {(postIn) -> Bool in + XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {postIn -> Bool in postIn.id == post.id })) XCTAssertEqual(postsInEagerlyLoadedBlog[0].id, post.id) @@ -195,7 +198,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -216,7 +220,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + let queriedBlogOptional = try await Amplify.DataStore.query(Blog6V2.self, byId: blog.id) guard let queriedBlog = queriedBlogOptional else { XCTFail("Could not get blog") @@ -232,16 +236,18 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { guard let blog = await saveBlog(name: "name"), let post1 = await savePost(title: "title", blog: blog), - let post2 = await savePost(title: "title", blog: blog) else { + let post2 = await savePost(title: "title", blog: blog) + else { XCTFail("Could not create blog, posts") return } - + let createReceived = expectation(description: "Create notification received") createReceived.expectedFulfillmentCount = 3 // 3 models (1 blog and 2 posts) let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -276,7 +282,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + var resultPosts: List? let queriedBlogOptional = try await Amplify.DataStore.query(Blog6V2.self, byId: blog.id) guard let queriedBlog = queriedBlogOptional else { @@ -297,19 +303,21 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { func testSaveBlogPostComment() async throws { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() - + guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } - + let createReceived = expectation(description: "Create notification received") createReceived.expectedFulfillmentCount = 3 // 3 models (1 blog and 1 post and 1 comment) let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -344,7 +352,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + var resultPosts: List? let queriedBlogOptional = try await Amplify.DataStore.query(Blog6V2.self, byId: blog.id) guard let queriedBlog = queriedBlogOptional else { @@ -353,14 +361,14 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { } XCTAssertEqual(queriedBlog.id, blog.id) resultPosts = queriedBlog.posts - + guard let posts = resultPosts else { XCTFail("Could not get posts") return } try await posts.fetch() XCTAssertEqual(posts.count, 1) - guard let fetchedPost = posts.first(where: { (postFetched) -> Bool in + guard let fetchedPost = posts.first(where: { postFetched -> Bool in postFetched.id == post.id }), let comments = fetchedPost.comments else { XCTFail("Could not set up - failed to get a post and its comments") @@ -368,7 +376,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { } try await comments.fetch() XCTAssertEqual(comments.count, 1) - XCTAssertTrue(comments.contains(where: { (commentFetched) -> Bool in + XCTAssertTrue(comments.contains(where: { commentFetched -> Bool in commentFetched.id == comment.id })) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) @@ -379,7 +387,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } @@ -387,7 +396,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 blog and 1 post and 1 comment) var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -423,7 +433,8 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { deleteReceived.expectedFulfillmentCount = 3 // 3 models due to cascade delete behavior hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -450,7 +461,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + _ = try await Amplify.DataStore.delete(blog) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) @@ -461,7 +472,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { var result: Blog6V2? do { result = try await Amplify.DataStore.save(blog) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -472,7 +483,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { var result: Post6V2? do { result = try await Amplify.DataStore.save(post) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -483,7 +494,7 @@ class DataStoreConnectionScenario6V2Tests: SyncEngineIntegrationV2TestBase { var result: Comment6V2? do { result = try await Amplify.DataStore.save(comment) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario7V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario7V2Tests.swift index 965c4ffe53..23de02b50b 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario7V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario7V2Tests.swift @@ -53,7 +53,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { let post1 = await savePost(title: "title", blog: blog), let _ = await savePost(title: "title", blog: blog), let comment1post1 = await saveComment(post: post1, content: "content"), - let comment2post1 = await saveComment(post: post1, content: "content") else { + let comment2post1 = await saveComment(post: post1, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } @@ -64,28 +65,28 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { return } XCTAssertEqual(queriedBlog.id, blog.id) - + resultPosts = queriedBlog.posts guard let posts = resultPosts else { XCTFail("Could not get posts") return } - + try await posts.fetch() XCTAssertEqual(posts.count, 2) - guard let fetchedPost = posts.first(where: { (post) -> Bool in + guard let fetchedPost = posts.first(where: { post -> Bool in post.id == post1.id }), let comments = fetchedPost.comments else { XCTFail("Could not set up - failed to get a post and its comments") return } - + try await comments.fetch() XCTAssertEqual(comments.count, 2) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment1post1.id })) - XCTAssertTrue(comments.contains(where: { (comment) -> Bool in + XCTAssertTrue(comments.contains(where: { comment -> Bool in comment.id == comment2post1.id })) if let post = comments[0].post { @@ -99,7 +100,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, post, and comment") return } @@ -133,7 +135,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, post, and comment") return } @@ -155,7 +158,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { if let postsInEagerlyLoadedBlog = eagerlyLoadedBlog.posts { try await postsInEagerlyLoadedBlog.fetch() XCTAssertEqual(postsInEagerlyLoadedBlog.count, 1) - XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {(postIn) -> Bool in + XCTAssertTrue(postsInEagerlyLoadedBlog.contains(where: {postIn -> Bool in postIn.id == post.id })) XCTAssertEqual(postsInEagerlyLoadedBlog[0].id, post.id) @@ -190,7 +193,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -225,7 +229,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post1 = await savePost(title: "title", blog: blog), - let post2 = await savePost(title: "title", blog: blog) else { + let post2 = await savePost(title: "title", blog: blog) + else { XCTFail("Could not create blog, posts") return } @@ -233,7 +238,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 blog and 2 posts) let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -277,7 +283,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { } XCTAssertEqual(queriedBlog.id, blog.id) resultPosts = queriedBlog.posts - + guard let posts = resultPosts else { XCTFail("Could not get posts") return @@ -292,7 +298,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } @@ -300,7 +307,8 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 blog and 1 post and 1 comment) let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -335,7 +343,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + var resultPosts: List? let queriedBlogOptional = try await Amplify.DataStore.query(Blog7V2.self, byId: blog.id) guard let queriedBlog = queriedBlogOptional else { @@ -344,14 +352,14 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { } XCTAssertEqual(queriedBlog.id, blog.id) resultPosts = queriedBlog.posts - + guard let posts = resultPosts else { XCTFail("Could not get posts") return } try await posts.fetch() XCTAssertEqual(posts.count, 1) - guard let fetchedPost = posts.first(where: { (postFetched) -> Bool in + guard let fetchedPost = posts.first(where: { postFetched -> Bool in postFetched.id == post.id }), let comments = fetchedPost.comments else { XCTFail("Could not set up - failed to get a post and its comments") @@ -359,7 +367,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { } try await comments.fetch() XCTAssertEqual(comments.count, 1) - XCTAssertTrue(comments.contains(where: { (commentFetched) -> Bool in + XCTAssertTrue(comments.contains(where: { commentFetched -> Bool in commentFetched.id == comment.id })) await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) @@ -370,14 +378,17 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), - var post = await savePost(title: "title", blog: blog) else { + var post = await savePost(title: "title", blog: blog) + else { XCTFail("Could not create blog and post") return } let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -400,8 +411,10 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { let updateReceived = expectation(description: "received updated post from sync event") let updatedTitle = "updatedTitle" post.title = updatedTitle - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -428,14 +441,17 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { await setUp(withModels: TestModelRegistration()) try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), - let post = await savePost(title: "title", blog: blog) else { + let post = await savePost(title: "title", blog: blog) + else { XCTFail("Could not create blog and post") return } - + let createReceived = expectation(description: "received post from sync event") - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -454,10 +470,12 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { return } await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "received deleted post from sync event") - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -484,14 +502,17 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let blog = await saveBlog(name: "name"), let post = await savePost(title: "title", blog: blog), - let comment = await saveComment(post: post, content: "content") else { + let comment = await saveComment(post: post, content: "content") + else { XCTFail("Could not create blog, posts, and comments") return } let createReceived = expectation(description: "received created from sync event") createReceived.expectedFulfillmentCount = 3 // 1 blog, 1 post, 1 comment - var hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + var hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -527,8 +548,10 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "received deleted from sync event") deleteReceived.expectedFulfillmentCount = 3 // 1 blog, 1 post, 1 comment - hubListener = Amplify.Hub.listen(to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + hubListener = Amplify.Hub.listen( + to: .dataStore, + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Could not cast payload to mutation event") return @@ -566,7 +589,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { var result: Blog7V2? do { result = try await Amplify.DataStore.save(blog) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -577,7 +600,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { var result: Post7V2? do { result = try await Amplify.DataStore.save(post) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -588,7 +611,7 @@ class DataStoreConnectionScenario7V2Tests: SyncEngineIntegrationV2TestBase { var result: Comment7V2? do { result = try await Amplify.DataStore.save(comment) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario8V2Tests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario8V2Tests.swift index 03734fc643..c2e60d2d2a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario8V2Tests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreConnectionScenario8V2Tests.swift @@ -55,7 +55,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let attendee = await saveAttendee(), let meeting = await saveMeeting(), - let registration = await saveRegistration(meeting: meeting, attendee: attendee) else { + let registration = await saveRegistration(meeting: meeting, attendee: attendee) + else { XCTFail("Could not create attendee, meeting, registration") return } @@ -63,7 +64,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 attendee and 1 meeting and 1 registration) let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -107,7 +109,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } try await queriedAttendee.meetings?.fetch() XCTAssertEqual(queriedAttendee.meetings?.count, 1) - + let queriedMeetingOptional = try await Amplify.DataStore.query(Meeting8V2.self, byId: meeting.id) guard let queriedMeeting = queriedMeetingOptional else { XCTFail("Could not get meeting") @@ -131,7 +133,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 4 // 4 models (2 attendees and 1 meeting and 1 registration) var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -169,11 +172,12 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { return } await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let updateReceived = expectation(description: "Update notification received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -193,12 +197,12 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { XCTFail("Listener not registered for hub") return } - + registration.attendee = attendee2 let updatedRegistration = try await Amplify.DataStore.save(registration) XCTAssertEqual(updatedRegistration.attendee.id, attendee2.id) await fulfillment(of: [updateReceived], timeout: TestCommonConstants.networkTimeout) - + var queriedAttendeeOptional = try await Amplify.DataStore.query(Attendee8V2.self, byId: attendee.id) guard let queriedAttendee = queriedAttendeeOptional else { XCTFail("Could not get attendee") @@ -206,7 +210,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } try await queriedAttendee.meetings?.fetch() XCTAssertEqual(queriedAttendee.meetings?.count, 0) - + queriedAttendeeOptional = try await Amplify.DataStore.query(Attendee8V2.self, byId: attendee2.id) guard let queriedAttendee = queriedAttendeeOptional else { XCTFail("Could not get attendee") @@ -221,7 +225,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let attendee = await saveAttendee(), let meeting = await saveMeeting(), - let registration = await saveRegistration(meeting: meeting, attendee: attendee) else { + let registration = await saveRegistration(meeting: meeting, attendee: attendee) + else { XCTFail("Could not create attendee, meeting, registration") return } @@ -229,7 +234,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 attendee and 1 meeting and 1 registration) var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -265,11 +271,12 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { return } await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteRegistrationRecieved = expectation(description: "Delete registration received") hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -289,7 +296,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } let _ = try await Amplify.DataStore.delete(registration) await fulfillment(of: [deleteRegistrationRecieved], timeout: TestCommonConstants.networkTimeout) - + let queriedAttendeeOptional = try await Amplify.DataStore.query(Attendee8V2.self, byId: attendee.id) guard let queriedAttendee = queriedAttendeeOptional else { XCTFail("Could not get attendee") @@ -297,7 +304,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } try await queriedAttendee.meetings?.fetch() XCTAssertEqual(queriedAttendee.meetings?.count, 0) - + let queriedMeetingOptional = try await Amplify.DataStore.query(Meeting8V2.self, byId: meeting.id) guard let queriedMeeting = queriedMeetingOptional else { XCTFail("Could not get meeting") @@ -312,7 +319,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let attendee = await saveAttendee(), let meeting = await saveMeeting(), - let registration = await saveRegistration(meeting: meeting, attendee: attendee) else { + let registration = await saveRegistration(meeting: meeting, attendee: attendee) + else { XCTFail("Could not create attendee, meeting, registration") return } @@ -320,7 +328,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 attendee and 1 meeting and 1 registration) var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -356,12 +365,13 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { return } await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "Delete received") deleteReceived.expectedFulfillmentCount = 2 // attendee and registration hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -391,13 +401,13 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } } } - + _ = try await Amplify.DataStore.delete(attendee) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) - + let queriedAttendeeOptional = try await Amplify.DataStore.query(Attendee8V2.self, byId: attendee.id) XCTAssertNil(queriedAttendeeOptional) - + let queriedMeetingOptional = try await Amplify.DataStore.query(Meeting8V2.self, byId: meeting.id) guard let queriedMeeting = queriedMeetingOptional else { XCTFail("Could not get meeting") @@ -412,7 +422,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { try await startAmplifyAndWaitForSync() guard let attendee = await saveAttendee(), let meeting = await saveMeeting(), - let registration = await saveRegistration(meeting: meeting, attendee: attendee) else { + let registration = await saveRegistration(meeting: meeting, attendee: attendee) + else { XCTFail("Could not create attendee, meeting, registration") return } @@ -420,7 +431,8 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { createReceived.expectedFulfillmentCount = 3 // 3 models (1 attendee and 1 meeting and 1 registration) var hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -456,12 +468,13 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { return } await fulfillment(of: [createReceived], timeout: TestCommonConstants.networkTimeout) - + let deleteReceived = expectation(description: "Delete received") deleteReceived.expectedFulfillmentCount = 2 // meeting and registration hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") @@ -482,10 +495,10 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } } } - + _ = try await Amplify.DataStore.delete(meeting) await fulfillment(of: [deleteReceived], timeout: TestCommonConstants.networkTimeout) - + let queriedAttendeeOptional = try await Amplify.DataStore.query(Attendee8V2.self, byId: attendee.id) guard let queriedAttendee = queriedAttendeeOptional else { XCTFail("Could not get meeting") @@ -493,7 +506,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { } try await queriedAttendee.meetings?.fetch() XCTAssertEqual(queriedAttendee.meetings?.count, 0) - + let queriedMeetingOptional = try await Amplify.DataStore.query(Meeting8V2.self, byId: meeting.id) XCTAssertNil(queriedMeetingOptional) } @@ -503,7 +516,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { var result: Attendee8V2? do { result = try await Amplify.DataStore.save(attendee) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -514,7 +527,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { var result: Meeting8V2? do { result = try await Amplify.DataStore.save(meeting) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result @@ -525,7 +538,7 @@ class DataStoreConnectionScenario8V2Tests: SyncEngineIntegrationV2TestBase { var result: Registration8V2? do { result = try await Amplify.DataStore.save(registration) - } catch(let error) { + } catch (let error) { XCTFail("Failed \(error)") } return result diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithCustomTimestampTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithCustomTimestampTests.swift index cae0ffcc0a..f9dfac98f8 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithCustomTimestampTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithCustomTimestampTests.swift @@ -45,7 +45,8 @@ class DataStoreModelWithCustomTimestampTests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "Delete notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithDefaultValueTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithDefaultValueTests.swift index 9a4643ff8c..d074a5bcb3 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithDefaultValueTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithDefaultValueTests.swift @@ -39,14 +39,16 @@ class DataStoreModelWithDefaultValueTests: SyncEngineIntegrationV2TestBase { let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return } guard let todoEvent = try? mutationEvent.decodeModel() as? TodoWithDefaultValueV2, - todoEvent.id == todo.id else { + todoEvent.id == todo.id + else { return } @@ -90,14 +92,16 @@ class DataStoreModelWithDefaultValueTests: SyncEngineIntegrationV2TestBase { let createReceived = expectation(description: "Create notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") return } guard let todoEvent = try? mutationEvent.decodeModel() as? TodoWithDefaultValueV2, - todoEvent.id == todo.id else { + todoEvent.id == todo.id + else { return } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithSecondaryIndexTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithSecondaryIndexTests.swift index 88545d49c8..105871d894 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithSecondaryIndexTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreModelWithSecondaryIndexTests.swift @@ -44,7 +44,8 @@ class DataStoreModelWithSecondaryIndexTests: SyncEngineIntegrationV2TestBase { let deleteReceived = expectation(description: "Delete notification received") let hubListener = Amplify.Hub.listen( to: .dataStore, - eventName: HubPayload.EventName.DataStore.syncReceived) { payload in + eventName: HubPayload.EventName.DataStore.syncReceived + ) { payload in guard let mutationEvent = payload.data as? MutationEvent else { XCTFail("Can't cast payload as mutation event") diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreSchemaDriftTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreSchemaDriftTests.swift index e52dad6dd6..68f9d815b7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreSchemaDriftTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginV2Tests/TransformerV2/DataStoreSchemaDriftTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Combine +import XCTest @testable import Amplify @testable import AWSDataStorePlugin @@ -60,11 +60,13 @@ class DataStoreSchemaDriftTests: SyncEngineIntegrationV2TestBase { input.updateValue("THREE", forKey: "enumValue") var variables = [String: Any]() variables.updateValue(input, forKey: "input") - let requestWithEnumThree = GraphQLRequest(document: request.document, - variables: variables, - responseType: request.responseType, - decodePath: request.decodePath, - options: request.options) + let requestWithEnumThree = GraphQLRequest( + document: request.document, + variables: variables, + responseType: request.responseType, + decodePath: request.decodePath, + options: request.options + ) Amplify.API.mutate(request: requestWithEnumThree) { result in switch result { case .success(let response): diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSession.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSession.swift index 8beaab3986..774ab441f7 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSession.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSession.swift @@ -5,10 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import Amplify import AWSAPIPlugin +import Foundation enum AmplifyURLSessionState { case active @@ -26,7 +25,7 @@ class AmplifyURLSessionNoOperationDataTask: URLSessionDataTaskBehavior { } static let shared: AmplifyURLSessionNoOperationDataTask = - AmplifyURLSessionNoOperationDataTask(taskBehaviorIdentifier: -1) + .init(taskBehaviorIdentifier: -1) func cancel() { } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSessionFactory.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSessionFactory.swift index f99be07eaf..bc77388b51 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSessionFactory.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/AmplifyURLSessionFactory.swift @@ -5,9 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // - -import Foundation import AWSAPIPlugin +import Foundation class AmplifyURLSessionFactory: URLSessionBehaviorFactory { func makeSession(withDelegate delegate: URLSessionBehaviorDelegate?) -> URLSessionBehavior { @@ -15,10 +14,12 @@ class AmplifyURLSessionFactory: URLSessionBehaviorFactory { let configuration = URLSessionConfiguration.default configuration.tlsMinimumSupportedProtocolVersion = .TLSv12 configuration.tlsMaximumSupportedProtocolVersion = .TLSv13 - - let session = URLSession(configuration: configuration, - delegate: urlSessionDelegate, - delegateQueue: nil) + + let session = URLSession( + configuration: configuration, + delegate: urlSessionDelegate, + delegateQueue: nil + ) return AmplifyURLSession(session: session) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/DataStoreHubEvent.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/DataStoreHubEvent.swift index cce3a2ae39..932873d300 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/DataStoreHubEvent.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/DataStoreHubEvent.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSDataStorePlugin +import Foundation /// Initialize with `HubPayload`'s `eventName: String` and `data: Any?` fields to return an enum of events with their /// expected payloads in their respective types diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/HubListenerTestUtilities.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/HubListenerTestUtilities.swift index a6376c3805..ccf59e7852 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/HubListenerTestUtilities.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreHostApp/HubListenerTestUtilities.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import Amplify import Foundation +@testable import Amplify -struct HubListenerTestUtilities { +enum HubListenerTestUtilities { /// Blocks current thread until the listener with `token` is attached to the plugin. Returns `true` if the listener /// becomes present before the `timeout` expires, `false` otherwise. @@ -17,11 +17,13 @@ struct HubListenerTestUtilities { /// - Parameter plugin: the plugin on which the listener will be checked /// - Parameter timeout: the maximum length of time to wait for the listener to be registered /// - Throws: if the plugin cannot be cast to `AWSHubPlugin` - static func waitForListener(with token: UnsubscribeToken, - plugin: HubCategoryPlugin? = nil, - timeout: TimeInterval, - file: StaticString = #file, - line: UInt = #line) async throws -> Bool { + static func waitForListener( + with token: UnsubscribeToken, + plugin: HubCategoryPlugin? = nil, + timeout: TimeInterval, + file: StaticString = #file, + line: UInt = #line + ) async throws -> Bool { let plugin = try plugin ?? Amplify.Hub.getPlugin(for: AWSHubPlugin.key) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift index e6923fd0ed..4650e79c07 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift @@ -7,25 +7,25 @@ import XCTest +import AWSAPIPlugin import AWSPluginsCore import Combine -import AWSAPIPlugin @testable import Amplify @testable import AWSDataStorePlugin @testable import DataStoreHostApp class DataStoreStressBaseTest: XCTestCase { - + static let amplifyConfigurationFile = "testconfiguration/AWSAmplifyStressTests-amplifyconfiguration" let concurrencyLimit = 50 let networkTimeout = TimeInterval(180) - + func setUp(withModels models: AmplifyModelRegistration, logLevel: LogLevel = .error) async { - + continueAfterFailure = false Amplify.Logging.logLevel = logLevel - + do { let amplifyConfig = try TestConfigHelper.retrieveAmplifyConfiguration(forResource: Self.amplifyConfigurationFile) try Amplify.add(plugin: AWSDataStorePlugin(modelRegistration: models, configuration: .custom(syncMaxRecords: 100))) @@ -36,15 +36,15 @@ class DataStoreStressBaseTest: XCTestCase { return } } - + override func tearDown() async throws { await Amplify.reset() } - + func stopDataStore() async throws { try await Amplify.DataStore.stop() } - + func clearDataStore() async throws { try await Amplify.DataStore.clear() } @@ -61,8 +61,10 @@ class DataStoreStressBaseTest: XCTestCase { let eventReceived = expectation(description: "DataStore \(eventName) event") var token: UnsubscribeToken! - token = Amplify.Hub.listen(to: .dataStore, - eventName: eventName) { _ in + token = Amplify.Hub.listen( + to: .dataStore, + eventName: eventName + ) { _ in eventReceived.fulfill() Amplify.Hub.removeListener(token) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressTests.swift index 444bb65f76..f7f08184dc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressTests.swift @@ -7,16 +7,16 @@ import XCTest +import AWSAPIPlugin import AWSPluginsCore import Combine -import AWSAPIPlugin @testable import Amplify @testable import AWSDataStorePlugin @testable import DataStoreHostApp final class DataStoreStressTests: DataStoreStressBaseTest { - + struct TestModelRegistration: AmplifyModelRegistration { func registerModels(registry: ModelRegistry.Type) { registry.register(modelType: Post.self) @@ -24,9 +24,9 @@ final class DataStoreStressTests: DataStoreStressBaseTest { let version: String = "1" } - + // MARK: - Stress tests - + /// Perform concurrent saves and observe the data successfuly synced from cloud /// /// - Given: DataStore is in ready state @@ -41,13 +41,15 @@ final class DataStoreStressTests: DataStoreStressBaseTest { var posts = [Post]() for index in 0 ..< concurrencyLimit { - let post = Post(title: "title \(index)", - status: .active, - content: "content \(index)", - createdAt: .now()) + let post = Post( + title: "title \(index)", + status: .active, + content: "content \(index)", + createdAt: .now() + ) posts.append(post) } - + let postsSyncedToCloud = expectation(description: "All posts saved and synced to cloud") postsSyncedToCloud.expectedFulfillmentCount = concurrencyLimit @@ -69,7 +71,7 @@ final class DataStoreStressTests: DataStoreStressBaseTest { XCTFail("Failed \(error)") } } - + let capturedPosts = posts DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in @@ -77,10 +79,10 @@ final class DataStoreStressTests: DataStoreStressBaseTest { _ = try await Amplify.DataStore.save(capturedPosts[index]) } } - + await fulfillment(of: [postsSyncedToCloud], timeout: networkTimeout) } - + /// Perform concurrent saves and observe the data successfuly synced from cloud /// /// - Given: DataStore is in ready state @@ -95,7 +97,7 @@ final class DataStoreStressTests: DataStoreStressBaseTest { try await startDataStoreAndWaitForReady() let posts = await saveAndSyncPosts(concurrencyLimit: concurrencyLimit) - + let localQueryForPosts = expectation(description: "Query for the post is successful") localQueryForPosts.expectedFulfillmentCount = concurrencyLimit @@ -109,10 +111,10 @@ final class DataStoreStressTests: DataStoreStressBaseTest { localQueryForPosts.fulfill() } } - + await fulfillment(of: [localQueryForPosts], timeout: networkTimeout) } - + /// Perform concurrent saves and observe the data successfuly synced from cloud /// /// - Given: DataStore is in ready state @@ -127,7 +129,7 @@ final class DataStoreStressTests: DataStoreStressBaseTest { try await startDataStoreAndWaitForReady() let posts = await saveAndSyncPosts(concurrencyLimit: concurrencyLimit) - + let localQueryForPosts = expectation(description: "Query for the post is successful") localQueryForPosts.expectedFulfillmentCount = concurrencyLimit DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in @@ -142,10 +144,10 @@ final class DataStoreStressTests: DataStoreStressBaseTest { localQueryForPosts.fulfill() } } - + await fulfillment(of: [localQueryForPosts], timeout: networkTimeout) } - + /// Perform concurrent saves and observe the data successfuly synced from cloud. Then delete the items afterwards /// and ensure they have successfully synced from cloud /// @@ -160,12 +162,12 @@ final class DataStoreStressTests: DataStoreStressBaseTest { func testMultipleDelete() async throws { await setUp(withModels: TestModelRegistration(), logLevel: .verbose) try await startDataStoreAndWaitForReady() - + let posts = await saveAndSyncPosts(concurrencyLimit: concurrencyLimit) - + let postsDeletedLocally = expectation(description: "All posts deleted locally") postsDeletedLocally.expectedFulfillmentCount = concurrencyLimit - + let postsDeletedFromCloud = expectation(description: "All posts deleted and synced to cloud") postsDeletedFromCloud.expectedFulfillmentCount = concurrencyLimit @@ -176,7 +178,7 @@ final class DataStoreStressTests: DataStoreStressBaseTest { guard posts.contains(where: { $0.id == mutationEvent.modelId }) else { return } - + if mutationEvent.mutationType == MutationEvent.MutationType.delete.rawValue, mutationEvent.version == 1 { postsDeletedLocally.fulfill() @@ -189,29 +191,31 @@ final class DataStoreStressTests: DataStoreStressBaseTest { XCTFail("Failed \(error)") } } - + DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in Task { try await Amplify.DataStore.delete(posts[index]) } } - + await fulfillment(of: [postsDeletedLocally, postsDeletedFromCloud], timeout: networkTimeout) } - - + + // MARK: - Helpers - + func saveAndSyncPosts(concurrencyLimit: Int) async -> [Post] { var posts = [Post]() for index in 0 ..< concurrencyLimit { - let post = Post(title: "title \(index)", - status: .active, - content: "content \(index)", - createdAt: .now()) + let post = Post( + title: "title \(index)", + status: .active, + content: "content \(index)", + createdAt: .now() + ) posts.append(post) } - + let postsSyncedToCloud = expectation(description: "All posts saved and synced to cloud") postsSyncedToCloud.expectedFulfillmentCount = concurrencyLimit @@ -223,7 +227,7 @@ final class DataStoreStressTests: DataStoreStressBaseTest { guard postsCopy.contains(where: { $0.id == mutationEvent.modelId }) else { return } - + if mutationEvent.mutationType == MutationEvent.MutationType.create.rawValue, mutationEvent.version == 1 { postsSyncedToCloud.fulfill() @@ -233,16 +237,16 @@ final class DataStoreStressTests: DataStoreStressBaseTest { XCTFail("Failed \(error)") } } - + let capturedPosts = posts - + DispatchQueue.concurrentPerform(iterations: concurrencyLimit) { index in Task { _ = try await Amplify.DataStore.save(capturedPosts[index]) } } await fulfillment(of: [postsSyncedToCloud], timeout: networkTimeout) - + return capturedPosts } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/AmplifyModels.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/AmplifyModels.swift index 96eef29957..167804f3b4 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/AmplifyModels.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/AmplifyModels.swift @@ -9,11 +9,11 @@ import Amplify import Foundation -// Contains the set of classes that conforms to the `Model` protocol. +// Contains the set of classes that conforms to the `Model` protocol. -final public class AmplifyModels: AmplifyModelRegistration { +public final class AmplifyModels: AmplifyModelRegistration { public let version: String = "9ddf09113aaee75fdec53f41fd7a73d7" - + public func registerModels(registry: ModelRegistry.Type) { ModelRegistry.register(modelType: Post.self) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post+Schema.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post+Schema.swift index 96d24f0a99..a1b369d614 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post+Schema.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post+Schema.swift @@ -9,9 +9,9 @@ import Amplify import Foundation -extension Post { - // MARK: - CodingKeys - public enum CodingKeys: String, ModelKey { +public extension Post { + // MARK: - CodingKeys + enum CodingKeys: String, ModelKey { case id case title case status @@ -19,23 +19,23 @@ extension Post { case createdAt case updatedAt } - - public static let keys = CodingKeys.self - // MARK: - ModelSchema - - public static let schema = defineSchema { model in + + static let keys = CodingKeys.self + // MARK: - ModelSchema + + static let schema = defineSchema { model in let post = Post.keys - + model.authRules = [ rule(allow: .public, operations: [.create, .update, .delete, .read]) ] - + model.pluralName = "Posts" - + model.attributes( .primaryKey(fields: [post.id]) ) - + model.fields( .field(post.id, is: .required, ofType: .string), .field(post.title, is: .required, ofType: .string), diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post.swift index 3658db511f..c5a0adeaac 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/Models/Post.swift @@ -16,24 +16,30 @@ public struct Post: Model { public var content: String public var createdAt: Temporal.DateTime? public var updatedAt: Temporal.DateTime? - - public init(id: String = UUID().uuidString, - title: String, - status: PostStatus, - content: String) { - self.init(id: id, + + public init( + id: String = UUID().uuidString, + title: String, + status: PostStatus, + content: String + ) { + self.init( + id: id, title: title, status: status, content: content, createdAt: nil, - updatedAt: nil) + updatedAt: nil + ) } - internal init(id: String = UUID().uuidString, - title: String, - status: PostStatus, - content: String, - createdAt: Temporal.DateTime? = nil, - updatedAt: Temporal.DateTime? = nil) { + init( + id: String = UUID().uuidString, + title: String, + status: PostStatus, + content: String, + createdAt: Temporal.DateTime? = nil, + updatedAt: Temporal.DateTime? = nil + ) { self.id = id self.title = title self.status = status