diff --git a/Kinvey/Kinvey/AggregateOperation.swift b/Kinvey/Kinvey/AggregateOperation.swift index 7268c2855..c6918f6f7 100644 --- a/Kinvey/Kinvey/AggregateOperation.swift +++ b/Kinvey/Kinvey/AggregateOperation.swift @@ -49,11 +49,23 @@ class AggregateOperation: ReadOperation AnyRequest { + let initialObject: JsonDictionary + let reduceJSFunction: String + do { + initialObject = try aggregation.initialObject() + reduceJSFunction = try aggregation.reduceJSFunction() + } catch { + let result: ResultType = .failure(error) + let request = LocalRequest() + request.result = result + completionHandler?(result) + return AnyRequest(request) + } let request = client.networkRequestFactory.buildAppDataGroup( - collectionName: T.collectionName(), + collectionName: try! T.collectionName(), keys: aggregation.keys, - initialObject: aggregation.initialObject, - reduceJSFunction: aggregation.reduceJSFunction, + initialObject: initialObject, + reduceJSFunction: reduceJSFunction, condition: predicate, options: options, resultType: ResultType.self @@ -98,7 +110,7 @@ enum Aggregation { } } - var resultKey: String { + func resultKey() throws -> String { switch self { case .count: return "count" @@ -111,41 +123,41 @@ enum Aggregation { case .max: return "max" case .custom(_, _, _): - fatalError("Custom does not have a resultKey") + throw Error.invalidOperation(description: "Custom does not have a resultKey") } } - var initialObject: JsonDictionary { + func initialObject() throws -> JsonDictionary { switch self { case .custom(_, let initialObject, _): return initialObject case .count: - return [resultKey : 0] + return [try resultKey() : 0] case .sum: - return [resultKey : 0.0] + return [try resultKey() : 0.0] case .avg: return ["sum" : 0.0, "count" : 0] case .min: - return [resultKey : "Infinity"] + return [try resultKey() : "Infinity"] case .max: - return [resultKey : "-Infinity"] + return [try resultKey() : "-Infinity"] } } - var reduceJSFunction: String { + func reduceJSFunction() throws -> String { switch self { case .custom(_, _, let reduceJSFunction): return reduceJSFunction case .count(_): - return "function(doc, out) { out.\(resultKey)++; }" + return "function(doc, out) { out.\(try resultKey())++; }" case .sum(_, let sum): - return "function(doc, out) { out.\(resultKey) += doc.\(sum); }" + return "function(doc, out) { out.\(try resultKey()) += doc.\(sum); }" case .avg(_, let avg): - return "function(doc, out) { out.count++; out.sum += doc.\(avg); out.\(resultKey) = out.sum / out.count; }" + return "function(doc, out) { out.count++; out.sum += doc.\(avg); out.\(try resultKey()) = out.sum / out.count; }" case .min(_, let min): - return "function(doc, out) { out.\(resultKey) = Math.min(out.\(resultKey), doc.\(min)); }" + return "function(doc, out) { out.\(try resultKey()) = Math.min(out.\(try resultKey()), doc.\(min)); }" case .max(_, let max): - return "function(doc, out) { out.\(resultKey) = Math.max(out.\(resultKey), doc.\(max)); }" + return "function(doc, out) { out.\(try resultKey()) = Math.max(out.\(try resultKey()), doc.\(max)); }" } } diff --git a/Kinvey/Kinvey/Cache.swift b/Kinvey/Kinvey/Cache.swift index 1e056e3d9..eb2c3725f 100644 --- a/Kinvey/Kinvey/Cache.swift +++ b/Kinvey/Kinvey/Cache.swift @@ -107,7 +107,7 @@ internal class Cache where T: NSObject { init(persistenceId: String, ttl: TimeInterval? = nil) { self.persistenceId = persistenceId - self.collectionName = T.collectionName() + self.collectionName = try! T.collectionName() self.ttl = ttl } diff --git a/Kinvey/Kinvey/CacheManager.swift b/Kinvey/Kinvey/CacheManager.swift index e487d7be2..14a49bc6d 100644 --- a/Kinvey/Kinvey/CacheManager.swift +++ b/Kinvey/Kinvey/CacheManager.swift @@ -22,7 +22,7 @@ internal class CacheManager: NSObject { self.schemaVersion = schemaVersion } - func cache(fileURL: URL? = nil, type: T.Type) -> AnyCache? where T: NSObject { + func cache(fileURL: URL? = nil, type: T.Type) throws -> AnyCache? where T: NSObject { let fileManager = FileManager.default if let fileURL = fileURL { do { @@ -33,7 +33,7 @@ internal class CacheManager: NSObject { } } - return AnyCache(RealmCache(persistenceId: persistenceId, fileURL: fileURL, encryptionKey: encryptionKey, schemaVersion: schemaVersion)) + return AnyCache(try RealmCache(persistenceId: persistenceId, fileURL: fileURL, encryptionKey: encryptionKey, schemaVersion: schemaVersion)) } func fileCache(fileURL: URL? = nil) -> AnyFileCache? { diff --git a/Kinvey/Kinvey/Client.swift b/Kinvey/Kinvey/Client.swift index be4715527..9459b32b4 100644 --- a/Kinvey/Kinvey/Client.swift +++ b/Kinvey/Kinvey/Client.swift @@ -182,9 +182,9 @@ open class Client: Credential { } } - private func validateInitialize(appKey: String, appSecret: String) { + private func validateInitialize(appKey: String, appSecret: String) throws { if appKey.isEmpty || appSecret.isEmpty { - fatalError("Please provide a valid appKey and appSecret. Your app's key and secret can be found on the Kinvey management console.") + throw Error.invalidOperation(description: "Please provide a valid appKey and appSecret. Your app's key and secret can be found on the Kinvey management console.") } } @@ -219,9 +219,14 @@ open class Client: Credential { encrypted: Bool, schema: Schema? = nil, options: Options? = nil, - completionHandler: @escaping (Result) -> Void) - { - validateInitialize(appKey: appKey, appSecret: appSecret) + completionHandler: @escaping (Result) -> Void + ) { + do { + try validateInitialize(appKey: appKey, appSecret: appSecret) + } catch { + completionHandler(.failure(error)) + return + } var encryptionKey: Data? = nil if encrypted { @@ -302,12 +307,14 @@ open class Client: Credential { ) { let apiHostNameString = "https://\(instanceId)-baas.kinvey.com" guard let apiHostName = URL(string: apiHostNameString) else { - fatalError("Invalid InstanceID: \(instanceId). \(apiHostNameString) is not a valid URL.") + completionHandler(.failure(Error.invalidOperation(description: "Invalid InstanceID: \(instanceId). \(apiHostNameString) is not a valid URL."))) + return } let authHostNameString = "https://\(instanceId)-auth.kinvey.com" guard let authHostName = URL(string: authHostNameString) else { - fatalError("Invalid InstanceID: \(instanceId). \(authHostNameString) is not a valid URL.") + completionHandler(.failure(Error.invalidOperation(description: "Invalid InstanceID: \(instanceId). \(authHostNameString) is not a valid URL."))) + return } return initialize( @@ -335,7 +342,13 @@ open class Client: Credential { options: Options? = nil, completionHandler: @escaping (Result) -> Void ) { - validateInitialize(appKey: appKey, appSecret: appSecret) + do { + try validateInitialize(appKey: appKey, appSecret: appSecret) + } catch { + completionHandler(.failure(error)) + return + } + self.encryptionKey = encryptionKey self.schemaVersion = schema?.version ?? 0 self.options = options @@ -373,7 +386,7 @@ open class Client: Credential { let customUser = user as! U completionHandler(.success(customUser)) } else if let kinveyAuth = sharedKeychain?.kinveyAuth { - User.login(authSource: .kinvey, kinveyAuth, options: Options(client: self)) { (result: Result) in + User.login(authSource: .kinvey, kinveyAuth, options: try! Options(client: self)) { (result: Result) in switch result { case .success(let user): completionHandler(.success(user)) @@ -404,11 +417,10 @@ open class Client: Credential { return self.appKey != nil && self.appSecret != nil } - internal func validate() -> Swift.Error? { + internal func validate() throws { guard isInitialized() else { - return Error.clientNotInitialized + throw Error.clientNotInitialized } - return nil } internal class func fileURL(appKey: String, tag: String = defaultTag) -> URL { @@ -447,10 +459,11 @@ open class Client: Credential { @discardableResult public func ping(completionHandler: @escaping (Result) -> Void) -> AnyRequest> { guard let _ = appKey, let _ = appSecret else { + let result: Result = .failure(Error.invalidOperation(description: "Please initialize your client calling the initialize() method before call ping()")) DispatchQueue.main.async { - completionHandler(.failure(Error.invalidOperation(description: "Please initialize your client calling the initialize() method before call ping()"))) + completionHandler(result) } - return AnyRequest(LocalRequest>()) + return AnyRequest(result) } let request = networkRequestFactory.buildAppDataPing( options: options, diff --git a/Kinvey/Kinvey/CountOperation.swift b/Kinvey/Kinvey/CountOperation.swift index 8ae401ed8..5b5eb515b 100644 --- a/Kinvey/Kinvey/CountOperation.swift +++ b/Kinvey/Kinvey/CountOperation.swift @@ -48,7 +48,7 @@ class CountOperation: ReadOperation, ReadOp func executeNetwork(_ completionHandler: CompletionHandler? = nil) -> AnyRequest { let request = client.networkRequestFactory.buildAppDataCountByQuery( - collectionName: T.collectionName(), + collectionName: try! T.collectionName(), query: query, options: options, resultType: ResultType.self diff --git a/Kinvey/Kinvey/CustomEndpoint.swift b/Kinvey/Kinvey/CustomEndpoint.swift index 7a3890d70..b854c065b 100644 --- a/Kinvey/Kinvey/CustomEndpoint.swift +++ b/Kinvey/Kinvey/CustomEndpoint.swift @@ -124,9 +124,7 @@ open class CustomEndpoint { return execute( name, params: params, - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) } @@ -201,9 +199,7 @@ open class CustomEndpoint { return execute( name, params: params, - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) } @@ -280,9 +276,7 @@ open class CustomEndpoint { return execute( name, params: params, - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) } @@ -357,9 +351,7 @@ open class CustomEndpoint { return execute( name, params: params, - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) } diff --git a/Kinvey/Kinvey/DataStore.swift b/Kinvey/Kinvey/DataStore.swift index 63cddb5cb..3e68de7af 100644 --- a/Kinvey/Kinvey/DataStore.swift +++ b/Kinvey/Kinvey/DataStore.swift @@ -88,14 +88,14 @@ open class DataStore where T: NSObject { tag: String = defaultTag, validationStrategy: ValidationStrategy? = nil, options: Options? = nil - ) -> DataStore { + ) throws -> DataStore { let client = options?.client ?? sharedClient let deltaSet = options?.deltaSet ?? false if !client.isInitialized() { - fatalError("Client is not initialized. Call Kinvey.sharedClient.initialize(...) to initialize the client before creating a DataStore.") + throw Error.invalidOperation(description: "Client is not initialized. Call Kinvey.sharedClient.initialize(...) to initialize the client before creating a DataStore.") } let fileURL = client.fileURL(tag) - let dataStore = DataStore( + let dataStore = try DataStore( type: type, deltaSet: deltaSet, autoPagination: autoPagination, @@ -115,8 +115,8 @@ open class DataStore where T: NSObject { */ open func collection( newType: NewType.Type - ) -> DataStore where NewType: NSObject { - return DataStore( + ) throws -> DataStore where NewType: NSObject { + return try DataStore( type: type, deltaSet: deltaSet, autoPagination: autoPagination, @@ -135,16 +135,16 @@ open class DataStore where T: NSObject { fileURL: URL?, encryptionKey: Data?, validationStrategy: ValidationStrategy? - ) { + ) throws { self.type = type self.deltaSet = deltaSet self.autoPagination = autoPagination self.client = client self.fileURL = fileURL - collectionName = T.collectionName() + collectionName = try! T.collectionName() if type != .network, let _ = T.self as? Entity.Type { - cache = client.cacheManager.cache(fileURL: fileURL, type: T.self) - sync = client.syncManager.sync(fileURL: fileURL, type: T.self) + cache = try client.cacheManager.cache(fileURL: fileURL, type: T.self) + sync = try client.syncManager.sync(fileURL: fileURL, type: T.self) } else { cache = nil sync = nil @@ -154,9 +154,9 @@ open class DataStore where T: NSObject { self.validationStrategy = validationStrategy } - private func validate(id: String) { + private func validate(id: String) throws { if id.isEmpty { - fatalError("id cannot be an empty string") + throw Error.invalidOperation(description: "id cannot be an empty string") } } @@ -173,7 +173,13 @@ open class DataStore where T: NSObject { options: Options? = nil, completionHandler: ((Result) -> Void)? = nil ) -> AnyRequest> { - validate(id: id) + do { + try validate(id: id) + } catch { + let result: Result = .failure(error) + completionHandler?(result) + return AnyRequest(result) + } let readPolicy = options?.readPolicy ?? self.readPolicy let operation = GetOperation( @@ -336,12 +342,12 @@ open class DataStore where T: NSObject { options: options ) let convert = { (results: [JsonDictionary]) -> [AggregationCountResult] in - let array = results.map { (json) -> AggregationCountResult in + let array = try results.map { (json) -> AggregationCountResult in var json = json json[Entity.EntityCodingKeys.entityId] = groupId return AggregationCountResult( value: try! client.jsonParser.parseObject(T.self, from: json), - count: json[aggregation.resultKey] as! Count + count: json[try aggregation.resultKey()] as! Count ) } return array @@ -350,7 +356,13 @@ open class DataStore where T: NSObject { switch result { case .success(let results): DispatchQueue.main.async { - completionHandler(.success(convert(results))) + let result: Result<[AggregationCountResult], Swift.Error> + do { + result = .success(try convert(results)) + } catch { + result = .failure(error) + } + completionHandler(result) } case .failure(let error): DispatchQueue.main.async { @@ -362,7 +374,13 @@ open class DataStore where T: NSObject { if let result = $0 { switch result { case .success(let results): - return .success(convert(results)) + let result: Result<[AggregationCountResult], Swift.Error> + do { + result = .success(try convert(results)) + } catch { + result = .failure(error) + } + return result case .failure(let error): return .failure(error) } @@ -392,12 +410,12 @@ open class DataStore where T: NSObject { options: options ) let convert = { (results: [JsonDictionary]) -> [AggregationSumResult] in - let array = results.map { (json) -> AggregationSumResult in + let array = try results.map { (json) -> AggregationSumResult in var json = json json[Entity.EntityCodingKeys.entityId] = groupId return AggregationSumResult( value: try! client.jsonParser.parseObject(T.self, from: json), - sum: json[aggregation.resultKey] as! Sum + sum: json[try aggregation.resultKey()] as! Sum ) } return array @@ -406,7 +424,13 @@ open class DataStore where T: NSObject { switch result { case .success(let results): DispatchQueue.main.async { - completionHandler(.success(convert(results))) + let result: Result<[AggregationSumResult], Swift.Error> + do { + result = .success(try convert(results)) + } catch { + result = .failure(error) + } + completionHandler(result) } case .failure(let error): DispatchQueue.main.async { @@ -418,7 +442,13 @@ open class DataStore where T: NSObject { if let result = $0 { switch result { case .success(let results): - return .success(convert(results)) + let result: Result<[AggregationSumResult], Swift.Error> + do { + result = .success(try convert(results)) + } catch { + result = .failure(error) + } + return result case .failure(let error): return .failure(error) } @@ -448,12 +478,12 @@ open class DataStore where T: NSObject { options: options ) let convert = { (results: [JsonDictionary]) -> [AggregationAvgResult] in - let array = results.map { (json) -> AggregationAvgResult in + let array = try results.map { (json) -> AggregationAvgResult in var json = json json[Entity.EntityCodingKeys.entityId] = groupId return AggregationAvgResult( value: try! client.jsonParser.parseObject(T.self, from: json), - avg: json[aggregation.resultKey] as! Avg + avg: json[try aggregation.resultKey()] as! Avg ) } return array @@ -462,7 +492,13 @@ open class DataStore where T: NSObject { switch result { case .success(let results): DispatchQueue.main.async { - completionHandler(.success(convert(results))) + let result: Result<[AggregationAvgResult], Swift.Error> + do { + result = .success(try convert(results)) + } catch { + result = .failure(error) + } + completionHandler(result) } case .failure(let error): DispatchQueue.main.async { @@ -474,7 +510,13 @@ open class DataStore where T: NSObject { if let result = $0 { switch result { case .success(let results): - return .success(convert(results)) + let result: Result<[AggregationAvgResult], Swift.Error> + do { + result = .success(try convert(results)) + } catch { + result = .failure(error) + } + return result case .failure(let error): return .failure(error) } @@ -503,12 +545,12 @@ open class DataStore where T: NSObject { options: options ) let convert = { (results: [JsonDictionary]) -> [AggregationMinResult] in - let array = results.map { (json) -> AggregationMinResult in + let array = try results.map { (json) -> AggregationMinResult in var json = json json[Entity.EntityCodingKeys.entityId] = groupId return AggregationMinResult( value: try! self.client.jsonParser.parseObject(T.self, from: json), - min: json[aggregation.resultKey] as! Min + min: json[try aggregation.resultKey()] as! Min ) } return array @@ -517,7 +559,13 @@ open class DataStore where T: NSObject { switch result { case .success(let results): DispatchQueue.main.async { - completionHandler(.success(convert(results))) + let result: Result<[AggregationMinResult], Swift.Error> + do { + result = .success(try convert(results)) + } catch { + result = .failure(error) + } + completionHandler(result) } case .failure(let error): DispatchQueue.main.async { @@ -529,7 +577,13 @@ open class DataStore where T: NSObject { if let result = $0 { switch result { case .success(let results): - return .success(convert(results)) + let result: Result<[AggregationMinResult], Swift.Error> + do { + result = .success(try convert(results)) + } catch { + result = .failure(error) + } + return result case .failure(let error): return .failure(error) } @@ -558,12 +612,12 @@ open class DataStore where T: NSObject { options: options ) let convert = { (results: [JsonDictionary]) -> [AggregationMaxResult] in - let array = results.map { (json) -> AggregationMaxResult in + let array = try results.map { (json) -> AggregationMaxResult in var json = json json[Entity.EntityCodingKeys.entityId] = groupId return AggregationMaxResult( value: try! self.client.jsonParser.parseObject(T.self, from: json), - max: json[aggregation.resultKey] as! Max + max: json[try aggregation.resultKey()] as! Max ) } return array @@ -572,7 +626,13 @@ open class DataStore where T: NSObject { switch result { case .success(let results): DispatchQueue.main.async { - completionHandler(.success(convert(results))) + let result: Result<[AggregationMaxResult], Swift.Error> + do { + result = .success(try convert(results)) + } catch { + result = .failure(error) + } + completionHandler(result) } case .failure(let error): DispatchQueue.main.async { @@ -584,7 +644,13 @@ open class DataStore where T: NSObject { if let result = $0 { switch result { case .success(let results): - return .success(convert(results)) + let result: Result<[AggregationMaxResult], Swift.Error> + do { + result = .success(try convert(results)) + } catch { + result = .failure(error) + } + return result case .failure(let error): return .failure(error) } @@ -656,7 +722,13 @@ open class DataStore where T: NSObject { options: Options? = nil, completionHandler: ((Result) -> Void)? = nil ) -> AnyRequest> { - validate(id: id) + do { + try validate(id: id) + } catch { + let result: Result = .failure(error) + completionHandler?(result) + return AnyRequest(result) + } let writePolicy = options?.writePolicy ?? self.writePolicy let operation = RemoveByIdOperation( @@ -684,13 +756,14 @@ open class DataStore where T: NSObject { completionHandler: ((Result) -> Void)? ) -> AnyRequest> { guard !ids.isEmpty else { + let result: Result = .failure(Error.invalidOperation(description: "ids cannot be an empty array")) DispatchQueue.main.async { - completionHandler?(.failure(Error.invalidOperation(description: "ids cannot be an empty array"))) + completionHandler?(result) } - return AnyRequest(LocalRequest>()) + return AnyRequest(result) } - let query = Query(format: "\(T.entityIdProperty()) IN %@", ids as AnyObject) + let query = Query(format: "\(try! T.entityIdProperty()) IN %@", ids as AnyObject) return remove( query, options: options, @@ -760,9 +833,7 @@ open class DataStore where T: NSObject { completionHandler: ((Result) -> Void)? = nil ) -> AnyRequest> { return push( - options: Options( - timeout: timeout - ), + options: try! Options(timeout: timeout), completionHandler: completionHandler ) } @@ -776,8 +847,9 @@ open class DataStore where T: NSObject { var request: AnyRequest>! Promise { resolver in if type == .network { - request = AnyRequest(LocalRequest>()) - resolver.reject(MultipleErrors(errors: [Error.invalidDataStoreType])) + let error = MultipleErrors(errors: [Error.invalidDataStoreType]) + request = AnyRequest(.failure([error])) + resolver.reject(error) } else { let operation = PushOperation( sync: sync, @@ -814,9 +886,7 @@ open class DataStore where T: NSObject { return pull( query, deltaSetCompletionHandler: deltaSetCompletionHandler, - options: Options( - deltaSet: deltaSet - ) + options: try! Options(deltaSet: deltaSet) ) { (result: Result, Swift.Error>) in switch result { case .success(let entities): @@ -838,11 +908,13 @@ open class DataStore where T: NSObject { var request: AnyRequest, Swift.Error>>! Promise> { resolver in if type == .network { - request = AnyRequest(LocalRequest, Swift.Error>>()) - resolver.reject(Error.invalidDataStoreType) + let error = Error.invalidDataStoreType + request = AnyRequest(.failure(error)) + resolver.reject(error) } else if self.syncCount() > 0 { - request = AnyRequest(LocalRequest, Swift.Error>>()) - resolver.reject(Error.invalidOperation(description: "You must push all pending sync items before new data is pulled. Call push() on the data store instance to push pending items, or purge() to remove them.")) + let error = Error.invalidOperation(description: "You must push all pending sync items before new data is pulled. Call push() on the data store instance to push pending items, or purge() to remove them.") + request = AnyRequest(.failure(error)) + resolver.reject(error) } else { let deltaSet = options?.deltaSet ?? self.deltaSet let operation = PullOperation( @@ -916,9 +988,7 @@ open class DataStore where T: NSObject { let request = sync( query, deltaSetCompletionHandler: deltaSetCompletionHandler, - options: Options( - deltaSet: deltaSet - ) + options: try! Options(deltaSet: deltaSet) ) { (result: Result<(UInt, AnyRandomAccessCollection), [Swift.Error]>) in guard let completionHandler = completionHandler else { return @@ -955,8 +1025,9 @@ open class DataStore where T: NSObject { let requests = MultiRequest), [Swift.Error]>>() Promise<(UInt, AnyRandomAccessCollection)> { resolver in if type == .network { - requests += LocalRequest), [Swift.Error]>>() - resolver.reject(MultipleErrors(errors: [Error.invalidDataStoreType])) + let error = Error.invalidDataStoreType + requests += LocalRequest(error) + resolver.reject(error) } else { let request = push( options: options @@ -1023,10 +1094,8 @@ open class DataStore where T: NSObject { var request: AnyRequest>! Promise { resolver in if type == .network { - let localRequest = LocalRequest>() - request = AnyRequest(localRequest) let error = Error.invalidDataStoreType - localRequest.result = .failure(error) + request = AnyRequest(.failure(error)) resolver.reject(error) } else { let executor = Executor() diff --git a/Kinvey/Kinvey/Entity.swift b/Kinvey/Kinvey/Entity.swift index b17800b0a..ebc873c68 100644 --- a/Kinvey/Kinvey/Entity.swift +++ b/Kinvey/Kinvey/Entity.swift @@ -62,8 +62,8 @@ open class Entity: Object, Persistable { } /// Override this method and return the name of the collection for Kinvey. - open class func collectionName() -> String { - fatalError("Method \(#function) must be overridden") + open class func collectionName() throws -> String { + throw Error.invalidOperation(description: "Method \(#function) must be overridden") } /// The `_id` property mapped in the Kinvey backend. @@ -123,7 +123,7 @@ open class Entity: Object, Persistable { :nodoc: */ open override class func primaryKey() -> String? { - return entityIdProperty() + return try? entityIdProperty() } /** diff --git a/Kinvey/Kinvey/FileStore.swift b/Kinvey/Kinvey/FileStore.swift index 8e50647ce..c8fe856ac 100644 --- a/Kinvey/Kinvey/FileStore.swift +++ b/Kinvey/Kinvey/FileStore.swift @@ -127,6 +127,7 @@ open class FileStore { /// Uploads a `UIImage` in a PNG or JPEG format. @discardableResult + @available(*, deprecated: 3.18.0, message: "Please use FileStore.upload(_:image:imageRepresentation:options:completionHandler:) instead") open func upload( _ file: FileType, image: NSImage, @@ -138,9 +139,7 @@ open class FileStore { file, image: image, imageRepresentation: imageRepresentation, - options: Options( - ttl: ttl - ), + options: try! Options(ttl: ttl), completionHandler: completionHandler ) } @@ -205,9 +204,7 @@ open class FileStore { file, image: image, imageRepresentation: imageRepresentation, - options: Options( - ttl: ttl - ), + options: try! Options(ttl: ttl), completionHandler: completionHandler ) } @@ -268,9 +265,7 @@ open class FileStore { return upload( file, path: path, - options: Options( - ttl: ttl - ), + options: try! Options(ttl: ttl), completionHandler: completionHandler ) } @@ -326,9 +321,7 @@ open class FileStore { return upload( file, stream: stream, - options: Options( - ttl: ttl - ), + options: try! Options(ttl: ttl), completionHandler: completionHandler ) } @@ -418,9 +411,7 @@ open class FileStore { return upload( file, data: data, - options: Options( - ttl: ttl - ), + options: try! Options(ttl: ttl), completionHandler: completionHandler ) } @@ -806,9 +797,7 @@ open class FileStore { ) -> AnyRequest> { return refresh( file, - options: Options( - ttl: ttl - ), + options: try! Options(ttl: ttl), completionHandler: completionHandler ) } @@ -919,15 +908,15 @@ open class FileStore { } /// Returns the cached file, if exists. - open func cachedFile(_ file: FileType) -> FileType? { - let entityId = crashIfInvalid(file: file) + open func cachedFile(_ file: FileType) throws -> FileType? { + let entityId = try crashIfInvalid(file: file) return cachedFile(entityId) } @discardableResult - fileprivate func crashIfInvalid(file: FileType) -> String { + fileprivate func crashIfInvalid(file: FileType) throws -> String { guard let fileId = file.fileId else { - fatalError("fileId is required") + throw Error.invalidOperation(description: "fileId is required") } return fileId } @@ -967,9 +956,7 @@ open class FileStore { return download( file, storeType: storeType, - options: Options( - ttl: ttl - ), + options: try! Options(ttl: ttl), completionHandler: completionHandler ) } @@ -982,7 +969,13 @@ open class FileStore { options: Options? = nil, completionHandler: ((Result<(FileType, URL), Swift.Error>) -> Void)? = nil ) -> AnyRequest> { - crashIfInvalid(file: file) + do { + try crashIfInvalid(file: file) + } catch { + let result: Result<(FileType, URL), Swift.Error> = .failure(error) + completionHandler?(result) + return AnyRequest(result) + } if storeType == .sync || storeType == .cache, let entityId = file.fileId, @@ -1085,9 +1078,7 @@ open class FileStore { ) -> AnyRequest> { return download( file, - options: Options( - ttl: ttl - ), + options: try! Options(ttl: ttl), completionHandler: completionHandler ) } @@ -1099,7 +1090,13 @@ open class FileStore { options: Options? = nil, completionHandler: ((Result<(FileType, Data), Swift.Error>) -> Void)? = nil ) -> AnyRequest> { - crashIfInvalid(file: file) + do { + try crashIfInvalid(file: file) + } catch { + let result: Result<(FileType, Data), Swift.Error> = .failure(error) + completionHandler?(result) + return AnyRequest(result) + } let multiRequest = MultiRequest>() multiRequest.progress = Progress(totalUnitCount: 100) @@ -1274,9 +1271,7 @@ open class FileStore { ) -> AnyRequest> { return find( query, - options: Options( - ttl: ttl - ), + options: try! Options(ttl: ttl), completionHandler: completionHandler ) } diff --git a/Kinvey/Kinvey/FindOperation.swift b/Kinvey/Kinvey/FindOperation.swift index cad41b5d0..49d235105 100644 --- a/Kinvey/Kinvey/FindOperation.swift +++ b/Kinvey/Kinvey/FindOperation.swift @@ -183,23 +183,19 @@ internal class FindOperation: ReadOperation AnyRandomAccessCollection { + func convertToEntities(fromJsonArray jsonArray: [JsonDictionary]) throws -> AnyRandomAccessCollection { let startTime = CFAbsoluteTimeGetCurrent() let client = options?.client ?? self.client - let entities = AnyRandomAccessCollection(jsonArray.lazy.map { (json) -> T in + let entities = AnyRandomAccessCollection(try jsonArray.lazy.map { (json) throws -> T in if let validationStrategy = self.validationStrategy { - do { - try validationStrategy.validate(jsonArray: [json]) - } catch { - fatalError(error.localizedDescription) - } + try validationStrategy.validate(jsonArray: [json]) } else { guard let entityId = json[Entity.EntityCodingKeys.entityId.rawValue] as? String, !entityId.isEmpty else { - fatalError("_id is required: \(T.self)\n\(json)") + throw Error.invalidOperation(description: "_id is required: \(T.self)\n\(json)") } } guard let entity = try? client.jsonParser.parseObject(T.self, from: json) else { - fatalError("Invalid entity creation: \(T.self)\n\(json)") + throw Error.invalidOperation(description: "Invalid entity creation: \(T.self)\n\(json)") } return entity }) @@ -210,7 +206,7 @@ internal class FindOperation: ReadOperation, sinceDate: Date) -> Promise> { return Promise> { resolver in let request = client.networkRequestFactory.buildAppDataFindByQueryDeltaSet( - collectionName: T.collectionName(), + collectionName: try! T.collectionName(), query: query, sinceDate: sinceDate, options: options @@ -226,22 +222,26 @@ internal class FindOperation: ReadOperation: ReadOperation) -> Promise> { return Promise> { resolver in let request = client.networkRequestFactory.buildAppDataFindByQuery( - collectionName: T.collectionName(), + collectionName: try! T.collectionName(), query: query, options: options ) @@ -312,31 +312,35 @@ internal class FindOperation: ReadOperation: ReadOperation(keys) let deleted = deleted.subtracting(refKeys) if deleted.count > 0 { - let query = Query(format: "\(T.entityIdProperty()) IN %@", deleted as AnyObject) + let query = Query(format: "\(try! T.entityIdProperty()) IN %@", deleted as AnyObject) cache.remove(byQuery: query) } } diff --git a/Kinvey/Kinvey/GetOperation.swift b/Kinvey/Kinvey/GetOperation.swift index 5bf894e57..9f5dc13bc 100644 --- a/Kinvey/Kinvey/GetOperation.swift +++ b/Kinvey/Kinvey/GetOperation.swift @@ -47,7 +47,7 @@ internal class GetOperation: ReadOperation, R func executeNetwork(_ completionHandler: CompletionHandler?) -> AnyRequest { let request = client.networkRequestFactory.buildAppDataGetById( - collectionName: T.collectionName(), + collectionName: try! T.collectionName(), id: id, options: options, resultType: ResultType.self diff --git a/Kinvey/Kinvey/HttpRequest.swift b/Kinvey/Kinvey/HttpRequest.swift index 861c17dbb..bb8607e98 100644 --- a/Kinvey/Kinvey/HttpRequest.swift +++ b/Kinvey/Kinvey/HttpRequest.swift @@ -432,7 +432,8 @@ internal class HttpRequest: TaskProgressRequest, Request { let kinveyAuthToken = socialIdentity.kinvey, let refreshToken = kinveyAuthToken["refresh_token"] as? String { - MIC.login(refreshToken: refreshToken, authServiceId: self.client.clientId, options: self.options) { + let options = try! Options(self.options, authServiceId: self.client.clientId) + MIC.login(refreshToken: refreshToken, options: options) { switch $0 { case .success(let user): self.credential = user diff --git a/Kinvey/Kinvey/HttpRequestFactory.swift b/Kinvey/Kinvey/HttpRequestFactory.swift index f88a20074..379ff5cb9 100644 --- a/Kinvey/Kinvey/HttpRequestFactory.swift +++ b/Kinvey/Kinvey/HttpRequestFactory.swift @@ -345,6 +345,7 @@ class HttpRequestFactory: RequestFactory { options: Options?, resultType: Result.Type ) -> HttpRequest { + let client = options?.client ?? self.client let request = HttpRequest( httpMethod: .post, endpoint: Endpoint.appDataGroup(client: client, collectionName: collectionName), @@ -368,7 +369,7 @@ class HttpRequestFactory: RequestFactory { options: Options?, resultType: Result.Type ) -> HttpRequest { - let collectionName = T.collectionName() + let collectionName = try! T.collectionName() let client = options?.client ?? self.client var bodyObject = try! client.jsonParser.toJSON(persistable) let objId = bodyObject[Entity.EntityCodingKeys.entityId] as? String diff --git a/Kinvey/Kinvey/LocalRequest.swift b/Kinvey/Kinvey/LocalRequest.swift index 0e25821a9..d124da079 100644 --- a/Kinvey/Kinvey/LocalRequest.swift +++ b/Kinvey/Kinvey/LocalRequest.swift @@ -35,5 +35,10 @@ internal class LocalRequest: NSObject, Request { func cancel() { //do nothing } + + convenience init(_ result: ResultType) { + self.init() + self.result = result + } } diff --git a/Kinvey/Kinvey/MIC.swift b/Kinvey/Kinvey/MIC.swift index dc91e9d49..e40fe1194 100644 --- a/Kinvey/Kinvey/MIC.swift +++ b/Kinvey/Kinvey/MIC.swift @@ -268,7 +268,6 @@ open class MIC { @discardableResult class func login( refreshToken: String, - authServiceId: String?, options: Options?, completionHandler: ((Result) -> Void)? = nil ) -> AnyRequest> { @@ -276,9 +275,7 @@ open class MIC { let client = options?.client ?? sharedClient let request = client.networkRequestFactory.buildOAuthGrantRefreshToken( refreshToken: refreshToken, - options: Options( - authServiceId: authServiceId - ) + options: options ) request.execute { (data, response, error) in if let response = response, @@ -342,10 +339,10 @@ class MICLoginViewController: UIViewController, WKNavigationDelegate, UIWebViewD var activityIndicatorView: UIActivityIndicatorView! - let redirectURI: URL - let forceUIWebView: Bool - let options: Options? - let completionHandler: UserHandler + var redirectURI: URL! + var forceUIWebView: Bool! + var options: Options? + var completionHandler: UserHandler! @objc var webView: UIView! @@ -357,13 +354,14 @@ class MICLoginViewController: UIViewController, WKNavigationDelegate, UIWebViewD } } - init( + convenience init( redirectURI: URL, userType: UserType.Type, forceUIWebView: Bool = false, options: Options?, completionHandler: @escaping UserHandler ) { + self.init(nibName: nil, bundle: nil) self.redirectURI = redirectURI self.forceUIWebView = forceUIWebView self.options = options @@ -375,11 +373,6 @@ class MICLoginViewController: UIViewController, WKNavigationDelegate, UIWebViewD completionHandler(.failure(error)) } } - super.init(nibName: nil, bundle: nil) - } - - required init?(coder aDecoder: NSCoder) { - fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { diff --git a/Kinvey/Kinvey/Options.swift b/Kinvey/Kinvey/Options.swift index 060217555..b6592ca09 100644 --- a/Kinvey/Kinvey/Options.swift +++ b/Kinvey/Kinvey/Options.swift @@ -42,15 +42,11 @@ public struct Options { public var customRequestProperties: [String : Any]? /// Maximum size per result set coming from the backend. Default to 10k records. - public var maxSizePerResultSet: Int? { - willSet { - validate(maxSizePerResultSet: newValue) - } - } + public private(set) var maxSizePerResultSet: Int? - private func validate(maxSizePerResultSet value: Int?) { + private func validate(maxSizePerResultSet value: Int?) throws { if let value = value, value <= 0 { - fatalError("maxSizePerResultSet must be greater than 0 (zero)") + throw Error.invalidOperation(description: "maxSizePerResultSet must be greater than 0 (zero)") } } @@ -59,6 +55,7 @@ public struct Options { default values for all the other properties */ public init( + _ options: Options? = nil, client: Client? = nil, urlSession: URLSession? = nil, authServiceId: String? = nil, @@ -70,9 +67,7 @@ public struct Options { clientAppVersion: String? = nil, customRequestProperties: [String : Any]? = nil, maxSizePerResultSet: Int? = nil - ) { - validate(maxSizePerResultSet: maxSizePerResultSet) - + ) throws { self.client = client self.urlSession = urlSession self.authServiceId = authServiceId @@ -83,7 +78,8 @@ public struct Options { self.timeout = timeout self.clientAppVersion = clientAppVersion self.customRequestProperties = customRequestProperties - self.maxSizePerResultSet = maxSizePerResultSet + self.maxSizePerResultSet = maxSizePerResultSet ?? options?.maxSizePerResultSet + try validate(maxSizePerResultSet: self.maxSizePerResultSet) } } diff --git a/Kinvey/Kinvey/Persistable.swift b/Kinvey/Kinvey/Persistable.swift index 5d234b831..d85a98053 100644 --- a/Kinvey/Kinvey/Persistable.swift +++ b/Kinvey/Kinvey/Persistable.swift @@ -19,7 +19,7 @@ infix operator <- : DefaultPrecedence public protocol Persistable: JSONCodable { /// Provides the collection name to be matched with the backend. - static func collectionName() -> String + static func collectionName() throws -> String /// Default Constructor. init() @@ -125,7 +125,7 @@ struct PropertyMap: Sequence, IteratorProtocol, ExpressibleByDictionaryLiteral { extension Persistable { - static func propertyMappingReverse() -> [String : [String]] { + static func propertyMappingReverse() throws -> [String : [String]] { var results = [String : [String]]() for (key, (value, _)) in propertyMapping() { var properties = results[value] @@ -141,10 +141,10 @@ extension Persistable { let isEntity = self is Entity.Type let hintMessage = isEntity ? "Please call super.propertyMapping() inside your propertyMapping() method." : "Please add properties in your Persistable model class to map the missing properties." guard entityIdMapped else { - fatalError("Property \(Entity.EntityCodingKeys.entityId) (Entity.Key.entityId) is missing in the propertyMapping() method. \(hintMessage)") + throw Error.invalidOperation(description: "Property \(Entity.EntityCodingKeys.entityId) (Entity.Key.entityId) is missing in the propertyMapping() method. \(hintMessage)") } guard metadataMapped else { - fatalError("Property \(Entity.EntityCodingKeys.metadata) (Entity.Key.metadata) is missing in the propertyMapping() method. \(hintMessage)") + throw Error.invalidOperation(description: "Property \(Entity.EntityCodingKeys.metadata) (Entity.Key.metadata) is missing in the propertyMapping() method. \(hintMessage)") } } return results @@ -166,16 +166,16 @@ extension Persistable { return propertyMapping()[propertyName] } - internal static func entityIdProperty() -> String { - return propertyMappingReverse()[Entity.EntityCodingKeys.entityId]!.last! + internal static func entityIdProperty() throws -> String { + return try propertyMappingReverse()[Entity.EntityCodingKeys.entityId]!.last! } - internal static func aclProperty() -> String? { - return propertyMappingReverse()[Entity.EntityCodingKeys.acl]?.last + internal static func aclProperty() throws -> String? { + return try propertyMappingReverse()[Entity.EntityCodingKeys.acl]?.last } - internal static func metadataProperty() -> String? { - return propertyMappingReverse()[Entity.EntityCodingKeys.metadata]?.last + internal static func metadataProperty() throws -> String? { + return try propertyMappingReverse()[Entity.EntityCodingKeys.metadata]?.last } } @@ -193,22 +193,28 @@ extension Persistable where Self: NSObject { internal var entityId: String? { get { - return self[type(of: self).entityIdProperty()] as? String + guard let entityIdProperty = try? type(of: self).entityIdProperty() else { + return nil + } + return self[entityIdProperty] as? String } set { - self[type(of: self).entityIdProperty()] = newValue + guard let entityIdProperty = try? type(of: self).entityIdProperty() else { + return + } + self[entityIdProperty] = newValue } } internal var acl: Acl? { get { - if let aclKey = type(of: self).aclProperty() { + if let _aclKey = try? type(of: self).aclProperty(), let aclKey = _aclKey { return self[aclKey] as? Acl } return nil } set { - if let aclKey = type(of: self).aclProperty() { + if let _aclKey = try? type(of: self).aclProperty(), let aclKey = _aclKey { self[aclKey] = newValue } } @@ -216,13 +222,13 @@ extension Persistable where Self: NSObject { internal var metadata: Metadata? { get { - if let kmdKey = type(of: self).metadataProperty() { + if let _kmdKey = try? type(of: self).metadataProperty(), let kmdKey = _kmdKey { return self[kmdKey] as? Metadata } return nil } set { - if let kmdKey = type(of: self).metadataProperty() { + if let _kmdKey = try? type(of: self).metadataProperty(), let kmdKey = _kmdKey { self[kmdKey] = newValue } } diff --git a/Kinvey/Kinvey/PurgeOperation.swift b/Kinvey/Kinvey/PurgeOperation.swift index 53c93f925..f15db50d2 100644 --- a/Kinvey/Kinvey/PurgeOperation.swift +++ b/Kinvey/Kinvey/PurgeOperation.swift @@ -40,7 +40,7 @@ internal class PurgeOperation: SyncOperation { resolver in let client = options?.client ?? self.client let request = client.networkRequestFactory.buildAppDataGetById( - collectionName: T.collectionName(), + collectionName: try! T.collectionName(), id: objectId, options: options, resultType: ResultType.self @@ -71,7 +71,7 @@ internal class PurgeOperation: SyncOperation { resolver in if let objectId = pendingOperation.objectId { - let query = Query(format: "\(T.entityIdProperty()) == %@", objectId) + let query = Query(format: "\(try! T.entityIdProperty()) == %@", objectId) cache?.remove(byQuery: query) } sync.removePendingOperation(pendingOperation) diff --git a/Kinvey/Kinvey/Push.swift b/Kinvey/Kinvey/Push.swift index 813311a55..c9421a003 100644 --- a/Kinvey/Kinvey/Push.swift +++ b/Kinvey/Kinvey/Push.swift @@ -201,9 +201,7 @@ open class Push { completionHandler: ((Result) -> Void)? = nil ) { replaceAppDelegateMethods( - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) @@ -226,9 +224,7 @@ open class Push { registerForNotifications( authorizationOptions: authorizationOptions, categories: categories, - options: Options( - client: client - ) + options: try! Options(client: client) ) { (result: Result) in switch result { case .success(let granted): @@ -248,9 +244,7 @@ open class Push { return registerForNotifications( authorizationOptions: authorizationOptions, categories: categories, - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) } @@ -291,9 +285,7 @@ open class Push { _ completionHandler: BoolCompletionHandler? = nil ) { unRegisterDeviceToken( - options: Options( - client: client - ) + options: try! Options(client: client) ) { (result: Result) in switch result { case .success: @@ -310,9 +302,7 @@ open class Push { _ completionHandler: ((Result) -> Void)? = nil ) { return unRegisterDeviceToken( - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) } diff --git a/Kinvey/Kinvey/PushOperation.swift b/Kinvey/Kinvey/PushOperation.swift index 6809aae85..068911493 100644 --- a/Kinvey/Kinvey/PushOperation.swift +++ b/Kinvey/Kinvey/PushOperation.swift @@ -85,7 +85,7 @@ internal class PushOperation: SyncOperation: Cache, CacheType where T: NSObject lazy var entityType = T.self as! Entity.Type lazy var entityTypeClassName = entityType.className() - lazy var entityTypeCollectionName = entityType.collectionName() + lazy var entityTypeCollectionName = try! entityType.collectionName() var dynamic: DynamicCacheType? { return self @@ -75,9 +75,9 @@ internal class RealmCache: Cache, CacheType where T: NSObject return realm } - required init(persistenceId: String, fileURL: URL? = nil, encryptionKey: Data? = nil, schemaVersion: UInt64) { + required init(persistenceId: String, fileURL: URL? = nil, encryptionKey: Data? = nil, schemaVersion: UInt64) throws { if !(T.self is Entity.Type) { - fatalError("\(T.self) needs to be a Entity") + throw Error.invalidOperation(description: "\(T.self) needs to be a Entity") } var configuration = Realm.Configuration() if let fileURL = fileURL { @@ -303,7 +303,7 @@ internal class RealmCache: Cache, CacheType where T: NSObject } } - if let ttl = ttl, let kmdKey = T.metadataProperty() { + if let ttl = ttl, let _kmdKey = try? T.metadataProperty(), let kmdKey = _kmdKey { realmResults = realmResults.filter("\(kmdKey).lrt >= %@", Date().addingTimeInterval(-ttl)) } @@ -783,9 +783,9 @@ extension RealmCache: DynamicCacheType { log.verbose("Saving \(entities.count) object(s)") let propertyMapping = T.propertyMapping() try! write { realm in - entities.forEachAutoreleasepool { entity in + try entities.forEachAutoreleasepool { entity in var translatedEntity = JsonDictionary() - propertyMapping.forEachAutoreleasepool { (translatedKey, tuple) in + try propertyMapping.forEachAutoreleasepool { (translatedKey, tuple) in let (key, transform) = tuple if let transform = transform, let value = transform.transformFromJSON(entity[key]) as? NSObject, diff --git a/Kinvey/Kinvey/RealmSync.swift b/Kinvey/Kinvey/RealmSync.swift index 309300216..27f9a9365 100644 --- a/Kinvey/Kinvey/RealmSync.swift +++ b/Kinvey/Kinvey/RealmSync.swift @@ -17,13 +17,13 @@ class RealmSync: SyncType where T: NSObject { let executor: Executor let persistenceId: String - lazy var collectionName: String = T.collectionName() + lazy var collectionName: String = try! T.collectionName() lazy var entityType = T.self as! Entity.Type - required init(persistenceId: String, fileURL: URL? = nil, encryptionKey: Data? = nil, schemaVersion: UInt64) { + required init(persistenceId: String, fileURL: URL? = nil, encryptionKey: Data? = nil, schemaVersion: UInt64) throws { if !(T.self is Entity.Type) { - fatalError("\(T.self) needs to be a Entity") + throw Error.invalidOperation(description: "\(T.self) needs to be a Entity") } var configuration = Realm.Configuration() if let fileURL = fileURL { diff --git a/Kinvey/Kinvey/RemoveByIdOperation.swift b/Kinvey/Kinvey/RemoveByIdOperation.swift index 0a532f734..8b18c8ae9 100644 --- a/Kinvey/Kinvey/RemoveByIdOperation.swift +++ b/Kinvey/Kinvey/RemoveByIdOperation.swift @@ -20,10 +20,10 @@ internal class RemoveByIdOperation: RemoveOperation where T: options: Options? ) { self.objectId = objectId - let query = Query(format: "\(T.entityIdProperty()) == %@", objectId as Any) + let query = Query(format: "\(try! T.entityIdProperty()) == %@", objectId as Any) let client = options?.client ?? sharedClient let httpRequest = client.networkRequestFactory.buildAppDataRemoveById( - collectionName: T.collectionName(), + collectionName: try! T.collectionName(), objectId: objectId, options: options, resultType: Result.self diff --git a/Kinvey/Kinvey/RemoveByQueryOperation.swift b/Kinvey/Kinvey/RemoveByQueryOperation.swift index 1143ce2e3..bd09eac59 100644 --- a/Kinvey/Kinvey/RemoveByQueryOperation.swift +++ b/Kinvey/Kinvey/RemoveByQueryOperation.swift @@ -19,7 +19,7 @@ internal class RemoveByQueryOperation: RemoveOperation where ) { let client = options?.client ?? sharedClient let httpRequest = client.networkRequestFactory.buildAppDataRemoveByQuery( - collectionName: T.collectionName(), + collectionName: try! T.collectionName(), query: query, options: options, resultType: Result.self diff --git a/Kinvey/Kinvey/RemoveOperation.swift b/Kinvey/Kinvey/RemoveOperation.swift index 3dd4ac853..73fd099b5 100644 --- a/Kinvey/Kinvey/RemoveOperation.swift +++ b/Kinvey/Kinvey/RemoveOperation.swift @@ -41,7 +41,7 @@ class RemoveOperation: WriteOperation, WriteOperationTyp if let cache = self.cache { let realmObjects = cache.find(byQuery: self.query) count = Int(realmObjects.count) - let idKey = T.entityIdProperty() + let idKey = try! T.entityIdProperty() let objectIds = cache.detach(entities: realmObjects, query: self.query).compactMap { $0[idKey] as? String } diff --git a/Kinvey/Kinvey/Request.swift b/Kinvey/Kinvey/Request.swift index c4ec26e1c..c025da193 100644 --- a/Kinvey/Kinvey/Request.swift +++ b/Kinvey/Kinvey/Request.swift @@ -118,4 +118,10 @@ public class AnyRequest: NSObject, Request { _getProgress = { request.progress } } + convenience init(_ result: ResultType) { + let request = LocalRequest() + request.result = result + self.init(request) + } + } diff --git a/Kinvey/Kinvey/SyncManager.swift b/Kinvey/Kinvey/SyncManager.swift index 9943264ad..de5a6b55d 100644 --- a/Kinvey/Kinvey/SyncManager.swift +++ b/Kinvey/Kinvey/SyncManager.swift @@ -20,8 +20,8 @@ internal class SyncManager: NSObject { self.schemaVersion = schemaVersion } - func sync(fileURL: URL? = nil, type: T.Type) -> AnySync where T: NSObject { - let realmSync = RealmSync(persistenceId: persistenceId, fileURL: fileURL, encryptionKey: encryptionKey, schemaVersion: schemaVersion) + func sync(fileURL: URL? = nil, type: T.Type) throws -> AnySync where T: NSObject { + let realmSync = try RealmSync(persistenceId: persistenceId, fileURL: fileURL, encryptionKey: encryptionKey, schemaVersion: schemaVersion) let anySync = AnySync(realmSync) return anySync } diff --git a/Kinvey/Kinvey/User.swift b/Kinvey/Kinvey/User.swift index 37adb17c8..e5606f73d 100644 --- a/Kinvey/Kinvey/User.swift +++ b/Kinvey/Kinvey/User.swift @@ -136,9 +136,7 @@ open class User: NSObject, Credential { username: username, password: password, user: user, - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) } @@ -183,11 +181,14 @@ open class User: NSObject, Credential { completionHandler: ((Result) -> Void)? = nil ) -> AnyRequest> { let client = options?.client ?? sharedClient - if let error = client.validate() { + do { + try client.validate() + } catch { + let result: Result = .failure(error) DispatchQueue.main.async { - completionHandler?(.failure(error)) + completionHandler?(result) } - return AnyRequest(LocalRequest>()) + return AnyRequest(result) } let request = client.networkRequestFactory.buildUserSignUp( @@ -311,7 +312,7 @@ open class User: NSObject, Credential { authSource: authSource, authData, createIfNotExists: createIfNotExists, - options: Options( + options: try! Options( client: client, authServiceId: authServiceId ), @@ -335,11 +336,14 @@ open class User: NSObject, Credential { completionHandler: ((Result) -> Void)? = nil ) -> AnyRequest> { let client = options?.client ?? sharedClient - if let error = client.validate() { + do { + try client.validate() + } catch { + let result: Result = .failure(error) DispatchQueue.main.async { - completionHandler?(.failure(error)) + completionHandler?(result) } - return AnyRequest(LocalRequest>()) + return AnyRequest(result) } let requests = MultiRequest>() @@ -404,9 +408,7 @@ open class User: NSObject, Credential { return login( username: username, password: password, - options: Options( - client: client - ) + options: try! Options(client: client) ) { (result: Result) in switch result { case .success(let user): @@ -435,9 +437,7 @@ open class User: NSObject, Credential { ) -> AnyRequest> { return sendEmailConfirmation( forUsername: username, - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) } @@ -505,10 +505,11 @@ open class User: NSObject, Credential { completionHandler: ((Result) -> Void)? = nil ) -> AnyRequest> { guard let _ = email else { + let result: Result = .failure(Error.invalidOperation(description: "Email is required to send the email confirmation")) DispatchQueue.main.async { - completionHandler?(.failure(Error.invalidOperation(description: "Email is required to send the email confirmation"))) + completionHandler?(result) } - return AnyRequest(LocalRequest>()) + return AnyRequest(result) } return User.sendEmailConfirmation( @@ -528,9 +529,7 @@ open class User: NSObject, Credential { ) -> AnyRequest> { return resetPassword( usernameOrEmail: usernameOrEmail, - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) } @@ -574,12 +573,14 @@ open class User: NSObject, Credential { options: options, completionHandler: completionHandler ) - } else if let completionHandler = completionHandler { + } + let result: Result = .failure(Error.userWithoutEmailOrUsername) + if let completionHandler = completionHandler { DispatchQueue.main.async(execute: { () -> Void in - completionHandler(.failure(Error.userWithoutEmailOrUsername)) + completionHandler(result) }) } - return AnyRequest(LocalRequest>()) + return AnyRequest(result) } /** @@ -660,9 +661,7 @@ open class User: NSObject, Credential { ) -> AnyRequest> { return forgotUsername( email: email, - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) } @@ -724,9 +723,7 @@ open class User: NSObject, Credential { ) -> AnyRequest> { return exists( username: username, - options: Options( - client: client - ), + options: try! Options(client: client), completionHandler: completionHandler ) } @@ -796,7 +793,7 @@ open class User: NSObject, Credential { ) -> AnyRequest> { return get( userId: userId, - options: Options( + options: try! Options( client: client ), completionHandler: completionHandler @@ -1238,7 +1235,7 @@ open class User: NSObject, Credential { redirectURI: redirectURI, username: username, password: password, - options: Options( + options: try! Options( client: client, authServiceId: authServiceId ), @@ -1280,11 +1277,14 @@ open class User: NSObject, Credential { switch provider { case .kinvey: let client = options?.client ?? sharedClient - if let error = client.validate() { + do { + try client.validate() + } catch { + let result: Result = .failure(error) DispatchQueue.main.async { - completionHandler?(.failure(error)) + completionHandler?(result) } - return AnyRequest(LocalRequest>()) + return AnyRequest(result) } let request = client.networkRequestFactory.buildUserLogin( @@ -1412,7 +1412,7 @@ open class User: NSObject, Credential { redirectURI: redirectURI, micUserInterface: micUserInterface, currentViewController: currentViewController, - options: Options( + options: try! Options( client: client, authServiceId: authServiceId, timeout: timeout @@ -1430,7 +1430,9 @@ open class User: NSObject, Credential { completionHandler: ((Result) -> Void)? = nil ) { let client = options?.client ?? sharedClient - if let error = client.validate() { + do { + try client.validate() + } catch { DispatchQueue.main.async { completionHandler?(.failure(error)) } diff --git a/Kinvey/KinveyApp/MICAuthorizationGrantViewController.swift b/Kinvey/KinveyApp/MICAuthorizationGrantViewController.swift index 03de3af72..1858cba7e 100644 --- a/Kinvey/KinveyApp/MICAuthorizationGrantViewController.swift +++ b/Kinvey/KinveyApp/MICAuthorizationGrantViewController.swift @@ -47,7 +47,7 @@ class MICAuthorizationGrantViewController: UIViewController { ) { user, error in if let user = user { self.labelUserID.text = user.userId - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) { store.find { diff --git a/Kinvey/KinveyApp/PerformanceTestData.swift b/Kinvey/KinveyApp/PerformanceTestData.swift index 0fb826b1b..4041b8693 100644 --- a/Kinvey/KinveyApp/PerformanceTestData.swift +++ b/Kinvey/KinveyApp/PerformanceTestData.swift @@ -14,7 +14,7 @@ class PerformanceTestData: UIViewController { let client = Client(appKey: "kid_b1d6IY_x7l", appSecret: "079412ee99f4485d85e6e362fb987de8") func store() -> DataStore where T: NSObject { - return DataStore.collection(.network, options: Options(client: self.client)) + return try! DataStore.collection(.network, options: try! Options(client: self.client)) } @IBOutlet dynamic weak var startDateLabel: UILabel! diff --git a/Kinvey/KinveyApp/PerformanceTestLongData.swift b/Kinvey/KinveyApp/PerformanceTestLongData.swift index f60e5ec8a..575ffed17 100644 --- a/Kinvey/KinveyApp/PerformanceTestLongData.swift +++ b/Kinvey/KinveyApp/PerformanceTestLongData.swift @@ -14,7 +14,7 @@ class PerformanceTestLongData: PerformanceTestData { override func test() { startDate = Date() let store: DataStore = self.store() - store.find(options: Options(deltaSet: deltaSetSwitch.isOn)) { + store.find(options: try! Options(deltaSet: deltaSetSwitch.isOn)) { self.endDate = Date() let count: Int switch $0 { diff --git a/Kinvey/KinveyApp/PerformanceTestMedData.swift b/Kinvey/KinveyApp/PerformanceTestMedData.swift index d8666030a..a5f530feb 100644 --- a/Kinvey/KinveyApp/PerformanceTestMedData.swift +++ b/Kinvey/KinveyApp/PerformanceTestMedData.swift @@ -14,7 +14,7 @@ class PerformanceTestMedData: PerformanceTestData { override func test() { startDate = Date() let store: DataStore = self.store() - store.find(options: Options(deltaSet: deltaSetSwitch.isOn)) { (result: Result, Swift.Error>) in + store.find(options: try! Options(deltaSet: deltaSetSwitch.isOn)) { (result: Result, Swift.Error>) in self.endDate = Date() switch result { case .success(let results): diff --git a/Kinvey/KinveyApp/PullDataStoreViewController.swift b/Kinvey/KinveyApp/PullDataStoreViewController.swift index c89eb35f6..3814b6591 100644 --- a/Kinvey/KinveyApp/PullDataStoreViewController.swift +++ b/Kinvey/KinveyApp/PullDataStoreViewController.swift @@ -69,7 +69,7 @@ class PullDataStoreViewController: UIViewController { timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) let query = Query() query.limit = 50000 - let options = Options(timeout: TimeInterval(round(timeoutSlider.value))) + let options = try! Options(timeout: TimeInterval(round(timeoutSlider.value))) request = dataStore.pull(query, options: options) { self.timer = nil self.request = nil diff --git a/Kinvey/KinveyMacAppTests/MacOSOnlyTestCase.swift b/Kinvey/KinveyMacAppTests/MacOSOnlyTestCase.swift index 1d0bba4b0..f30fae5d1 100644 --- a/Kinvey/KinveyMacAppTests/MacOSOnlyTestCase.swift +++ b/Kinvey/KinveyMacAppTests/MacOSOnlyTestCase.swift @@ -12,7 +12,7 @@ import XCTest class MacOSOnlyTestCase: KinveyTestCase { func testCachePath() { - let dataStore = DataStore.collection(.sync) + let dataStore = try! DataStore.collection(.sync) let person = Person() person.name = "Victor" diff --git a/Kinvey/KinveyMacAppTests/PerformanceTest.swift b/Kinvey/KinveyMacAppTests/PerformanceTest.swift index a908337c1..31244d34f 100644 --- a/Kinvey/KinveyMacAppTests/PerformanceTest.swift +++ b/Kinvey/KinveyMacAppTests/PerformanceTest.swift @@ -82,7 +82,7 @@ class PerformanceTest: XCTestCase { let sapCustomerNumbersTotal = sapCustomerNumbers.reduce(0, { $0 + $1.value }) XCTAssertEqual(884463, sapCustomerNumbersTotal) - let dataStore = DataStore.collection() + let dataStore = try! DataStore.collection() dataStore.clearCache() Kinvey.logLevel = .warning @@ -126,7 +126,7 @@ class PerformanceTest: XCTestCase { print("Time elapsed to count \(sapCustomerNumber): \(CFAbsoluteTimeGetCurrent() - startTime) s.") } - Kinvey.sharedClient.options = Options(timeout: 600) + Kinvey.sharedClient.options = try! Options(timeout: 600) let limit = 10000 measure { @@ -235,7 +235,7 @@ class PerformanceTest: XCTestCase { let sapCustomerNumbersTotal = sapCustomerNumbers.reduce(0, { $0 + $1.value }) XCTAssertEqual(884463, sapCustomerNumbersTotal) - let dataStore = DataStore.collection(autoPagination: true) + let dataStore = try! DataStore.collection(autoPagination: true) dataStore.clearCache() Kinvey.logLevel = .warning @@ -279,7 +279,7 @@ class PerformanceTest: XCTestCase { print("Time elapsed to count \(sapCustomerNumber): \(CFAbsoluteTimeGetCurrent() - startTime) s.") } - Kinvey.sharedClient.options = Options(timeout: 600) + Kinvey.sharedClient.options = try! Options(timeout: 600) measure { let startTime = CFAbsoluteTimeGetCurrent() diff --git a/Kinvey/KinveyTests/AclTestCase.swift b/Kinvey/KinveyTests/AclTestCase.swift index 3c1fdb699..bd931c61c 100644 --- a/Kinvey/KinveyTests/AclTestCase.swift +++ b/Kinvey/KinveyTests/AclTestCase.swift @@ -14,13 +14,13 @@ class AclTestCase: StoreTestCase { func testNoPermissionToDelete() { signUp() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) let person = save(newPerson) signUp() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) if useMockData { mockResponse(statusCode: 401, json: [ @@ -79,13 +79,13 @@ class AclTestCase: StoreTestCase { func testNoPermissionToDeletePush() { signUp() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) let person = save(newPerson) signUp() - store = DataStore.collection(.sync) + store = try! DataStore.collection(.sync) do { if useMockData { @@ -110,7 +110,7 @@ class AclTestCase: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(person.personId!, options: Options(readPolicy: .forceNetwork)) { + store.find(person.personId!, options: try! Options(readPolicy: .forceNetwork)) { self.assertThread() switch $0 { case .success(let person): @@ -196,7 +196,7 @@ class AclTestCase: StoreTestCase { func testGlobalRead() { signUp() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) guard let userId = Kinvey.sharedClient.activeUser?.userId else { return @@ -257,7 +257,7 @@ class AclTestCase: StoreTestCase { func testGlobalWrite() { signUp() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) let newPerson = self.newPerson newPerson.acl = Acl(creator: sharedClient.activeUser!.userId, globalWrite: true) @@ -321,7 +321,7 @@ class AclTestCase: StoreTestCase { signUp() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) let newPerson = self.newPerson newPerson.acl = Acl(creator: sharedClient.activeUser!.userId, readers: [user.userId]) @@ -387,7 +387,7 @@ class AclTestCase: StoreTestCase { signUp() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) let newPerson = self.newPerson newPerson.acl = Acl(creator: sharedClient.activeUser!.userId, writers: [user.userId]) diff --git a/Kinvey/KinveyTests/CacheMigrationTestCaseStep1.swift b/Kinvey/KinveyTests/CacheMigrationTestCaseStep1.swift index 0c3279508..4821b0a26 100644 --- a/Kinvey/KinveyTests/CacheMigrationTestCaseStep1.swift +++ b/Kinvey/KinveyTests/CacheMigrationTestCaseStep1.swift @@ -67,7 +67,7 @@ class CacheMigrationTestCaseStep1: XCTestCase { } } - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) let person = Person() person.firstName = "Victor" diff --git a/Kinvey/KinveyTests/CacheMigrationTestCaseStep2.swift b/Kinvey/KinveyTests/CacheMigrationTestCaseStep2.swift index 7e7cf0847..c6bce6be3 100644 --- a/Kinvey/KinveyTests/CacheMigrationTestCaseStep2.swift +++ b/Kinvey/KinveyTests/CacheMigrationTestCaseStep2.swift @@ -113,7 +113,7 @@ class CacheMigrationTestCaseStep2: XCTestCase { XCTAssertTrue(migrationCalled) XCTAssertTrue(migrationPersonCalled) - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) weak var expectationFind = expectation(description: "Find") @@ -154,7 +154,7 @@ class CacheMigrationTestCaseStep2: XCTestCase { XCTAssertTrue(migrationCalled) - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) weak var expectationFind = expectation(description: "Find") @@ -195,7 +195,7 @@ class CacheMigrationTestCaseStep2: XCTestCase { } } - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) weak var expectationFind = expectation(description: "Find") diff --git a/Kinvey/KinveyTests/CacheStoreTests.swift b/Kinvey/KinveyTests/CacheStoreTests.swift index 8a447e1c6..2bd0c2bd9 100644 --- a/Kinvey/KinveyTests/CacheStoreTests.swift +++ b/Kinvey/KinveyTests/CacheStoreTests.swift @@ -17,15 +17,15 @@ class CacheStoreTests: StoreTestCase { signUp() - store = DataStore.collection(.cache) + store = try! DataStore.collection(.cache) } var mockCount = 0 override func tearDown() { if let activeUser = client.activeUser { - let store = DataStore.collection(.network) - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) + let store = try! DataStore.collection(.network) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) if useMockData { mockResponse(json: ["count" : mockCount]) @@ -145,7 +145,7 @@ class CacheStoreTests: StoreTestCase { if let temporaryObjectId = temporaryObjectId { weak var expectationFind = expectation(description: "Find") - store.find(temporaryObjectId, options: Options(readPolicy: .forceLocal)) { + store.find(temporaryObjectId, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let person): XCTFail() @@ -165,7 +165,7 @@ class CacheStoreTests: StoreTestCase { if let finalObjectId = finalObjectId { weak var expectationRemove = expectation(description: "Remove") - store.remove(byId: finalObjectId, options: Options(writePolicy: .forceLocal)) { + store.remove(byId: finalObjectId, options: try! Options(writePolicy: .forceLocal)) { switch $0 { case .success(let count): XCTAssertEqual(count, 1) @@ -214,7 +214,7 @@ class CacheStoreTests: StoreTestCase { weak var expectationSaveNetwork = expectation(description: "Save Network") weak var expectationSaveLocal = expectation(description: "Save Local") - let store = DataStore.collection(.cache) + let store = try! DataStore.collection(.cache) store.save(book) { switch $0 { case .success(let book): @@ -243,7 +243,7 @@ class CacheStoreTests: StoreTestCase { do { weak var expectationFind = expectation(description: "Find") - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) store.find { switch $0 { case .success(let books): @@ -269,7 +269,7 @@ class CacheStoreTests: StoreTestCase { do { weak var expectationFind = expectation(description: "Find") - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) let query = Query(format: "authorNames contains %@", "Victor Barros") store.find(query) { switch $0 { @@ -296,7 +296,7 @@ class CacheStoreTests: StoreTestCase { do { weak var expectationFind = expectation(description: "Find") - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) let query = Query(format: "subquery(authorNames, $authorNames, $authorNames like[c] %@).@count > 0", "Vic*") store.find(query) { switch $0 { @@ -374,7 +374,7 @@ class CacheStoreTests: StoreTestCase { weak var expectationSaveNetwork = expectation(description: "Save Network") weak var expectationSaveLocal = expectation(description: "Save Local") - let store = DataStore.collection(.cache) + let store = try! DataStore.collection(.cache) store.save(book) { switch $0 { case .success(let book): @@ -404,7 +404,7 @@ class CacheStoreTests: StoreTestCase { weak var expectationFindLocal = expectation(description: "Save Local") weak var expectationFindNetwork = expectation(description: "Save Network") - let store = DataStore.collection(.cache) + let store = try! DataStore.collection(.cache) store.find { switch $0 { case .success(let books): @@ -447,7 +447,7 @@ class CacheStoreTests: StoreTestCase { //Create 1 person, Make regular GET, Create 1 more person, Make regular GET func testCacheStoreDisabledDeltasetWithPull() { - let store = DataStore.collection(.cache) + let store = try! DataStore.collection(.cache) var initialCount = Int64(0) do { @@ -611,7 +611,7 @@ class CacheStoreTests: StoreTestCase { } //Create 1 person, Make regular GET, Create 1 more person, Make deltaset request func testCacheStoreDeltaset1ExtraItemAddedWithPull() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var sinceTime = Date().toString() var initialCount = Int64(0) do { @@ -769,7 +769,7 @@ class CacheStoreTests: StoreTestCase { } //Create 1 person, Make regular GET,Make deltaset request func testCacheStoreDeltasetSinceIsRespectedWithoutChangesWithPull() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -898,7 +898,7 @@ class CacheStoreTests: StoreTestCase { } //Create 2 persons, pull with regular GET, update 1, deltaset returning 1 changed, delete 1, deltaset returning 1 deleted func testCacheStoreDeltaset1ItemAdded1Updated1DeletedWithPull() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var idToUpdate = "" var idToDelete = "" @@ -1133,7 +1133,7 @@ class CacheStoreTests: StoreTestCase { } //Created 3 items, 2 of which satisfy a query, pull with query with regular GET, delete 1 item that satisfies the query, deltaset returns 1 deleted item func testCacheStoreDeltaset1WithQuery1ItemDeletedWithPull() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var idToDelete = "" var initialCount = Int64(0) @@ -1299,7 +1299,7 @@ class CacheStoreTests: StoreTestCase { //Created 3 items, 2 of which satisfy a query, pull with query with regular GET, update 1 item that satisfies the query, deltaset returns 1 changed item func testCacheStoreDeltasetWithQuery1ItemUpdatedWithPull() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var idToUpdate = "" var initialCount = Int64(0) @@ -1485,7 +1485,7 @@ class CacheStoreTests: StoreTestCase { //Create 1 item, pull with regular GET, create another item, deltaset returns 1 changed, switch off deltaset, pull with regular GET func testCacheStoreDeltasetTurnedOffSendsRegularGETWithPull() { - var store = DataStore.collection(.cache, options: Options(deltaSet: true)) + var store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -1638,7 +1638,7 @@ class CacheStoreTests: StoreTestCase { expectationPull = nil } } - store = DataStore.collection(.cache, options: Options(deltaSet: false)) + store = try! DataStore.collection(.cache, options: try! Options(deltaSet: false)) do { if useMockData { mockResponse { (request) -> HttpResponse in @@ -1715,7 +1715,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDisabledDeltasetWithSync() { - let store = DataStore.collection(.cache) + let store = try! DataStore.collection(.cache) var initialCount = 0 do { @@ -1868,7 +1868,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDeltaset1ExtraItemAddedWithSync() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -2015,7 +2015,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDeltasetSinceIsRespectedWithoutChangesWithSync() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -2138,7 +2138,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDeltaset1ItemAdded1Updated1DeletedWithSync() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var idToUpdate = "" var idToDelete = "" @@ -2363,7 +2363,7 @@ class CacheStoreTests: StoreTestCase { func testCacheStoreDeltaset1WithQuery1ItemDeletedWithSync() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var idToDelete = "" var initialCount = Int64(0) @@ -2521,7 +2521,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDeltasetWithQuery1ItemUpdatedWithSync() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var idToUpdate = "" var initialCount = Int64(0) @@ -2701,7 +2701,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDeltasetTurnedOffSendsRegularGETWithSync() { - var store = DataStore.collection(.cache, options: Options(deltaSet: true)) + var store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -2847,7 +2847,7 @@ class CacheStoreTests: StoreTestCase { expectationSync = nil } } - store = DataStore.collection(.cache, options: Options(deltaSet: false)) + store = try! DataStore.collection(.cache, options: try! Options(deltaSet: false)) do { if useMockData { mockResponse { (request) -> HttpResponse in @@ -2920,7 +2920,7 @@ class CacheStoreTests: StoreTestCase { } } func testCacheStoreDisabledDeltasetWithFind() { - let store = DataStore.collection(.cache) + let store = try! DataStore.collection(.cache) var initialCount = Int64(0) do { @@ -2975,7 +2975,7 @@ class CacheStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") let query = Query() - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork store.find(query, options: options) { (result: Result, Swift.Error>) in switch result { @@ -3055,7 +3055,7 @@ class CacheStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") let query = Query() - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork store.find(query, options: options) { (result: Result, Swift.Error>) in switch result { @@ -3084,7 +3084,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDeltaset1ExtraItemAddedWithFind() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var initialCount = 0 do { @@ -3138,7 +3138,7 @@ class CacheStoreTests: StoreTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3213,7 +3213,7 @@ class CacheStoreTests: StoreTestCase { } } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork let query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3249,7 +3249,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDeltasetSinceIsRespectedWithoutChangesWithFind() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -3303,7 +3303,7 @@ class CacheStoreTests: StoreTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3357,7 +3357,7 @@ class CacheStoreTests: StoreTestCase { } } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3388,7 +3388,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDeltaset1ItemAdded1Updated1DeletedWithFind() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var idToUpdate = "" var idToDelete = "" @@ -3461,7 +3461,7 @@ class CacheStoreTests: StoreTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3541,7 +3541,7 @@ class CacheStoreTests: StoreTestCase { } } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3606,7 +3606,7 @@ class CacheStoreTests: StoreTestCase { } } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3637,7 +3637,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDeltaset1WithQuery1ItemDeletedWithFind() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var idToDelete = "" var initialCount = Int64(0) @@ -3715,7 +3715,7 @@ class CacheStoreTests: StoreTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query(format: "age == %@", 23) store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3781,7 +3781,7 @@ class CacheStoreTests: StoreTestCase { } } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query(format: "age == %@", 23) store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3812,7 +3812,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDeltasetWithQuery1ItemUpdatedWithFind() { - let store = DataStore.collection(.cache, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var idToUpdate = "" var initialCount = Int64(0) @@ -3890,7 +3890,7 @@ class CacheStoreTests: StoreTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query(format: "age == %@", 23) store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3973,7 +3973,7 @@ class CacheStoreTests: StoreTestCase { } } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query(format: "age == %@", 23) store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -4009,7 +4009,7 @@ class CacheStoreTests: StoreTestCase { } func testCacheStoreDeltasetTurnedOffSendsRegularGETWithFind() { - var store = DataStore.collection(.cache, options: Options(deltaSet: true)) + var store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -4063,7 +4063,7 @@ class CacheStoreTests: StoreTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -4139,7 +4139,7 @@ class CacheStoreTests: StoreTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -4171,7 +4171,7 @@ class CacheStoreTests: StoreTestCase { expectationFind = nil } } - store = DataStore.collection(.cache, options: Options(deltaSet: false)) + store = try! DataStore.collection(.cache, options: try! Options(deltaSet: false)) do { if useMockData { mockResponse { (request) -> HttpResponse in @@ -4218,7 +4218,7 @@ class CacheStoreTests: StoreTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -4254,7 +4254,7 @@ class CacheStoreTests: StoreTestCase { //Create 1 item, pull with regular GET, create another item, deltaset returns 1 changed, switch off deltaset, pull with regular GET func testCacheStoreFindByIdNotUsingDeltaset() { - var store = DataStore.collection(.cache, options: Options(deltaSet: true)) + var store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var idToFind = "" var initialCount = 0 var readPolicy = ReadPolicy.forceNetwork @@ -4310,7 +4310,7 @@ class CacheStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(idToFind, options: Options(readPolicy: readPolicy)) { + store.find(idToFind, options: try! Options(readPolicy: readPolicy)) { self.assertThread() switch $0 { @@ -4370,7 +4370,7 @@ class CacheStoreTests: StoreTestCase { } weak var expectationFind = expectation(description: "Find") - store.find(idToFind, options: Options(readPolicy: readPolicy)) { + store.find(idToFind, options: try! Options(readPolicy: readPolicy)) { self.assertThread() switch $0 { diff --git a/Kinvey/KinveyTests/ClientTestCase.swift b/Kinvey/KinveyTests/ClientTestCase.swift index 9aa1c04a9..14d61c0d1 100644 --- a/Kinvey/KinveyTests/ClientTestCase.swift +++ b/Kinvey/KinveyTests/ClientTestCase.swift @@ -226,16 +226,37 @@ class ClientTestCase: KinveyTestCase { } func testClientAppKeyAndAppSecretEmpty() { - expect { () -> Void in - let _ = Client(appKey: "", appSecret: "") - }.to(throwAssertion()) + weak var expectationClient = self.expectation(description: "Client") + + let client = Client(appKey: "", appSecret: "") { + switch $0 { + case .success: + XCTFail() + case .failure(let error): + let error = error as? Kinvey.Error + XCTAssertNotNil(error) + if let error = error { + switch error { + case .invalidOperation(let description): + XCTAssertEqual(description, "Please provide a valid appKey and appSecret. Your app's key and secret can be found on the Kinvey management console.") + default: + XCTFail(error.localizedDescription) + } + } + } + expectationClient?.fulfill() + } + + waitForExpectations(timeout: defaultTimeout) { (error) in + expectationClient = nil + } } func testDataStoreWithoutInitilizeClient() { expect { () -> Void in let client = Client() - let _ = DataStore.collection(options: Options(client: client)) - }.to(throwAssertion()) + try DataStore.collection(options: try! Options(client: client)) + }.to(throwError()) } func testDefaultMICVersion() { diff --git a/Kinvey/KinveyTests/DataTypeTestCase.swift b/Kinvey/KinveyTests/DataTypeTestCase.swift index bae8bc990..9fb0284b8 100644 --- a/Kinvey/KinveyTests/DataTypeTestCase.swift +++ b/Kinvey/KinveyTests/DataTypeTestCase.swift @@ -24,7 +24,7 @@ class DataTypeTestCase: StoreTestCase { func testSave() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) let dataType = DataType() dataType.boolValue = true dataType.colorValue = Color.orange @@ -128,7 +128,7 @@ class DataTypeTestCase: StoreTestCase { func testDate() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) let dateEntity = EntityWithDate() dateEntity.date = Date() @@ -189,7 +189,7 @@ class DataTypeTestCase: StoreTestCase { func testDatePull() { signUp() - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) if useMockData { mockResponse(json: [ diff --git a/Kinvey/KinveyTests/DateTestCase.swift b/Kinvey/KinveyTests/DateTestCase.swift index b35a37b40..db0f0dbe0 100644 --- a/Kinvey/KinveyTests/DateTestCase.swift +++ b/Kinvey/KinveyTests/DateTestCase.swift @@ -61,7 +61,7 @@ class DateTestCase: KinveyTestCase { func testQueryDate() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) let publishDate = Date() diff --git a/Kinvey/KinveyTests/DeltaSetCacheTestCase.swift b/Kinvey/KinveyTests/DeltaSetCacheTestCase.swift index 511c52647..041807d71 100644 --- a/Kinvey/KinveyTests/DeltaSetCacheTestCase.swift +++ b/Kinvey/KinveyTests/DeltaSetCacheTestCase.swift @@ -17,8 +17,8 @@ class DeltaSetCacheTestCase: KinveyTestCase { override func tearDown() { if let activeUser = client.activeUser { - let store = DataStore.collection(.network) - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) + let store = try! DataStore.collection(.network) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) if useMockData { mockResponse(json: ["count" : mockCount]) @@ -74,7 +74,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } let operation = Operation( cache: AnyCache(cache), - options: Options( + options: try! Options( client: client ) ) @@ -121,7 +121,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { return } - let store = DataStore.collection() + let store = try! DataStore.collection() let person = Person() person.name = "Victor" @@ -203,7 +203,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { let createOperation = SaveOperation( persistable: person, writePolicy: .forceNetwork, - options: Options( + options: try! Options( client: client ) ) @@ -223,13 +223,13 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) query.ascending("name") do { weak var expectationRead = expectation(description: "Read") - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 1) @@ -286,7 +286,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 2) @@ -317,7 +317,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { return } - let store = DataStore.collection() + let store = try! DataStore.collection() let person = Person() person.name = "Victor" @@ -403,7 +403,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { let updateOperation = SaveOperation( persistable: person, writePolicy: .forceNetwork, - options: Options( + options: try! Options( client: client ) ) @@ -423,13 +423,13 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) query.ascending("name") do { weak var expectationRead = expectation(description: "Read") - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 1) @@ -473,7 +473,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 1) @@ -501,7 +501,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { return } - let store = DataStore.collection() + let store = try! DataStore.collection() let person = Person() person.name = "Victor" @@ -574,7 +574,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { let createRemove = RemoveByQueryOperation( query: query, writePolicy: .forceNetwork, - options: Options( + options: try! Options( client: client ) ) @@ -594,13 +594,13 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) query.ascending("name") do { weak var expectationRead = expectation(description: "Read") - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 1) @@ -631,7 +631,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 0) @@ -685,7 +685,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { let createOperation = SaveOperation( persistable: person, writePolicy: .forceNetwork, - options: Options( + options: try! Options( client: self.client ) ) @@ -708,7 +708,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { let saveAndCache: (Int) -> Void = { i in let person = Person() person.name = String(format: "Person Cached %02d", i) - let store = DataStore.collection() + let store = try! DataStore.collection() if self.useMockData { self.mockResponse(statusCode: 201, json: [ @@ -732,7 +732,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationSave = self.expectation(description: "Save") - store.save(person, options: Options(writePolicy: .forceNetwork)) { + store.save(person, options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success: break @@ -756,15 +756,15 @@ class DeltaSetCacheTestCase: KinveyTestCase { saveAndCache(i) } - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) query.ascending("name") do { weak var expectationRead = expectation(description: "Read") - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 5) @@ -1015,7 +1015,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { let createOperation = SaveOperation( persistable: person, writePolicy: .forceNetwork, - options: Options( + options: try! Options( client: self.client ) ) @@ -1037,7 +1037,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } let saveAndCache: (Int) -> Void = { n in - let store = DataStore.collection() + let store = try! DataStore.collection() for i in 1...n { let person = Person() @@ -1065,15 +1065,15 @@ class DeltaSetCacheTestCase: KinveyTestCase { saveAndCache(countLocal) save(countBackend) - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) query.ascending("name") do { weak var expectationRead = self.expectation(description: "Read") - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, countLocal) @@ -1098,7 +1098,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { do { weak var expectationFind = self.expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, countBackend + countLocal) @@ -1147,8 +1147,8 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testFindEmpty() { signUp() - let store = DataStore.collection() - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) + let store = try! DataStore.collection() + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) if useMockData { mockResponse(json: []) @@ -1161,7 +1161,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 0) @@ -1180,7 +1180,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testPullAllRecords() { signUp() - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) let person = Person() person.name = "Victor" @@ -1263,7 +1263,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) weak var expectationPull = expectation(description: "Pull") @@ -1287,8 +1287,8 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testFindOneRecord() { signUp() - let store = DataStore.collection() - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) + let store = try! DataStore.collection() + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) class OnePersonURLProtocol: URLProtocol { @@ -1339,7 +1339,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 1) @@ -1362,7 +1362,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testFindOneRecordDeltaSetNoChange() { signUp() - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) let person = Person() person.name = "Victor" @@ -1425,7 +1425,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) do { var mockCount = 0 @@ -1460,7 +1460,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 1) @@ -1504,7 +1504,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in switch result { case .success(let results): XCTAssertEqual(results.count, 1) @@ -1528,7 +1528,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testFindOneRecordDeltaSetChanged() { signUp() - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) let person = Person() person.name = "Victor" @@ -1591,7 +1591,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) do { var mockCount = 0 @@ -1627,7 +1627,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 1) @@ -1684,7 +1684,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in switch result { case .success(let results): XCTAssertEqual(results.count, 1) @@ -1740,7 +1740,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(queryFields, options: Options(readPolicy: .forceNetwork)) { + store.find(queryFields, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 1) @@ -1796,7 +1796,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(queryFields, options: Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in + store.find(queryFields, options: try! Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in switch result { case .success(let results): XCTAssertEqual(results.count, 1) @@ -1821,7 +1821,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testFindOneRecordDeltaSetNoKmd() { signUp() - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) let person = Person() person.name = "Victor" @@ -1883,7 +1883,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) do { if useMockData { @@ -1909,7 +1909,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 1) @@ -1966,7 +1966,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in switch result { case .success(let results): XCTAssertEqual(results.count, 1) @@ -1988,7 +1988,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } func testFindOneRecordDeltaSetTimeoutError2ndRequest() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { let person = Person() @@ -2020,7 +2020,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -2039,7 +2039,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testFind201RecordsDeltaSet() { signUp() - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) let person = Person() person.name = "Victor" @@ -2094,7 +2094,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) var jsonArray = [JsonDictionary]() for _ in 1...201 { @@ -2120,7 +2120,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 201) @@ -2154,7 +2154,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 201) @@ -2174,7 +2174,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testFind201RecordsDeltaSetTimeoutOn2ndRequest() { signUp() - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) let person = Person() person.name = "Victor" @@ -2229,7 +2229,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", client.activeUser!.userId) var jsonArray = [JsonDictionary]() for _ in 1...201 { @@ -2253,7 +2253,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -2298,7 +2298,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) weak var expectationPull = expectation(description: "Pull") @@ -2351,7 +2351,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let store = DataStore.collection(.sync, autoPagination: true, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, autoPagination: true, options: try! Options(deltaSet: true)) weak var expectationPull = expectation(description: "Pull") @@ -2401,7 +2401,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { weak var expectationPull = expectation(description: "Pull") @@ -2452,7 +2452,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testDeltaSet3rdPull() { signUp() - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var date1: String? var date2: String? @@ -2590,7 +2590,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testDeltaSet3rdPullDifferentClassName() { signUp() - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var date1: String? var date2: String? @@ -2728,7 +2728,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testDeltaSetChangeFromSyncToCache() { signUp() - var store = DataStore.collection(.sync, options: Options(deltaSet: true)) + var store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var date1: String? var date2: String? @@ -2876,7 +2876,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - store = DataStore.collection(.cache, options: Options(deltaSet: true)) + store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) do { if useMockData{ @@ -2957,7 +2957,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testDeltaSetChangeFromCacheToSync() { signUp() - var store = DataStore.collection(.cache, options: Options(deltaSet: true)) + var store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) var date1: String? var date2: String? @@ -3105,7 +3105,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - store = DataStore.collection(.sync, options: Options(deltaSet: true)) + store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { if useMockData{ @@ -3186,7 +3186,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testDeltaSetChangeFromNetworkToCache() { signUp() - var store = DataStore.collection(.network, options: nil) + var store = try! DataStore.collection(.network, options: nil) var date1: String? var date2: String? @@ -3241,7 +3241,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3265,7 +3265,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - store = DataStore.collection(.cache, options: Options(deltaSet: true)) + store = try! DataStore.collection(.cache, options: try! Options(deltaSet: true)) do { if useMockData{ mockResponse { request in @@ -3424,7 +3424,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testDeltaSetChangeFromNetworkToSync() { signUp() - var store = DataStore.collection(.network, options: nil) + var store = try! DataStore.collection(.network, options: nil) var date1: String? var date2: String? @@ -3479,7 +3479,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -3503,7 +3503,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } } - store = DataStore.collection(.sync, options: Options(deltaSet: true)) + store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { if useMockData{ mockResponse { request in @@ -3662,7 +3662,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testDeltaSetLowercaseHeader() { signUp() - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var date1: String? var date2: String? @@ -3753,7 +3753,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testDeltaSetAndAutoPagination() { signUp() - let store = DataStore.collection(.sync, autoPagination: true, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, autoPagination: true, options: try! Options(deltaSet: true)) let count = useMockData ? 3 : try! store.count(options: Options(readPolicy: .forceNetwork)).waitForResult(timeout: defaultTimeout).value() @@ -3885,7 +3885,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testServerSideDeltaSetMissingConfiguration() { signUp() - let dataStore = DataStore.collection(.sync, options: Options(deltaSet: true)) + let dataStore = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var count: Int? = nil @@ -3980,7 +3980,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testServerSideDeltaSetMissingConfigurationAutoPaginationOn() { signUp() - let dataStore = DataStore.collection(.sync, autoPagination: true, options: Options(deltaSet: true)) + let dataStore = try! DataStore.collection(.sync, autoPagination: true, options: try! Options(deltaSet: true)) var count: Int? = nil @@ -4075,7 +4075,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { } do { - let options = Options(maxSizePerResultSet: 3) + let options = try! Options(maxSizePerResultSet: 3) let results = try dataStore.pull(options: options).waitForResult(timeout: defaultTimeout).value() XCTAssertEqual(results.count, count2) } catch { @@ -4086,7 +4086,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testServerSideDeltaSetParameterValueOutOfRange() { signUp() - let dataStore = DataStore.collection(.sync, options: Options(deltaSet: true)) + let dataStore = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var count: Int? = nil @@ -4206,7 +4206,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testDeltaSetHandler() { signUp() - let dataStore = DataStore.collection(.sync, options: Options(deltaSet: true)) + let dataStore = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { mockResponse { request in @@ -4355,7 +4355,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testServerSideDeltaSetQueryWithFields() { signUp() - let dataStore = DataStore.collection(.sync, options: Options(deltaSet: true)) + let dataStore = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) let json = [ [ @@ -4497,10 +4497,10 @@ class DeltaSetCacheTestCase: KinveyTestCase { func serverSideDeltaSetResultSetSizeExceeded(autoPagination: Bool) { signUp() - let dataStore = DataStore.collection( + let dataStore = try! DataStore.collection( .sync, autoPagination: autoPagination, - options: Options(deltaSet: true) + options: try! Options(deltaSet: true) ) var count: Int? = nil @@ -4644,10 +4644,10 @@ class DeltaSetCacheTestCase: KinveyTestCase { func testServerSideDeltaSetAutoPagination2ndRequestFailing() { signUp() - let dataStore = DataStore.collection( + let dataStore = try! DataStore.collection( .sync, autoPagination: true, - options: Options(deltaSet: true) + options: try! Options(deltaSet: true) ) var count: Int? = nil @@ -4744,7 +4744,7 @@ class DeltaSetCacheTestCase: KinveyTestCase { return } - let options = Options(maxSizePerResultSet: 1) + let options = try! Options(maxSizePerResultSet: 1) do { let results = try dataStore.pull(options: options).waitForResult(timeout: defaultTimeout).value() @@ -4768,15 +4768,12 @@ class DeltaSetCacheTestCase: KinveyTestCase { } func testMaxSizePerResultSetGreaterThanZero() { - expect { () -> Void? in - let _ = Options(maxSizePerResultSet: 0) - return nil - }.to(throwAssertion()) - expect { () -> Void? in - var options = Options() - options.maxSizePerResultSet = 0 - return nil - }.to(throwAssertion()) + expect { + try Options(maxSizePerResultSet: 0) + }.to(throwError()) + expect { + try Options(Options(maxSizePerResultSet: 1), maxSizePerResultSet: 0) + }.to(throwError()) } } diff --git a/Kinvey/KinveyTests/EncryptedDataStoreTestCase.swift b/Kinvey/KinveyTests/EncryptedDataStoreTestCase.swift index dd711f048..67269c6ae 100644 --- a/Kinvey/KinveyTests/EncryptedDataStoreTestCase.swift +++ b/Kinvey/KinveyTests/EncryptedDataStoreTestCase.swift @@ -30,7 +30,7 @@ class EncryptedDataStoreTestCase: StoreTestCase { func testEncryptedDataStore() { signUp() - store = DataStore.collection(.network, options: Options(client: client)) + store = try! DataStore.collection(.network, options: try! Options(client: client)) save(newPerson) } diff --git a/Kinvey/KinveyTests/EntityTestCase.swift b/Kinvey/KinveyTests/EntityTestCase.swift index 26b5081b1..082db9e47 100644 --- a/Kinvey/KinveyTests/EntityTestCase.swift +++ b/Kinvey/KinveyTests/EntityTestCase.swift @@ -13,9 +13,9 @@ import Nimble class EntityTestCase: XCTestCase { func testCollectionName() { - expect { () -> Void in - let _ = Entity.collectionName() - }.to(throwAssertion()) + expect { + try Entity.collectionName() + }.to(throwError()) } func testBoolValue() { diff --git a/Kinvey/KinveyTests/FileTestCase.swift b/Kinvey/KinveyTests/FileTestCase.swift index 5bcfed1c1..b57063a34 100644 --- a/Kinvey/KinveyTests/FileTestCase.swift +++ b/Kinvey/KinveyTests/FileTestCase.swift @@ -137,11 +137,27 @@ class FileTestCase: StoreTestCase { func testDownloadMissingFileId() { signUp() - expect { () -> Void in - self.fileStore.download(File()) { (file, data: Data?, error) in - XCTFail() + weak var expectationDownload = expectation(description: "Download") + + self.fileStore.download(File()) { (file, data: Data?, error) in + XCTAssertNil(file) + XCTAssertNil(data) + XCTAssertNotNil(error) + if let error = error as? Kinvey.Error { + switch error { + case .invalidOperation(let description): + XCTAssertEqual(description, "fileId is required") + default: + XCTFail(error.localizedDescription) + } } - }.to(throwAssertion()) + + expectationDownload?.fulfill() + } + + waitForExpectations(timeout: defaultTimeout) { error in + expectationDownload = nil + } } func testDownloadTimeoutError() { @@ -3036,7 +3052,9 @@ class FileTestCase: StoreTestCase { let file = File() { $0.fileId = UUID().uuidString } - XCTAssertNil(fileStore.cachedFile(file)) + expect { + try self.fileStore.cachedFile(file) + }.to(beNil()) } func testCreateBucketData() { diff --git a/Kinvey/KinveyTests/FindOperationTest.swift b/Kinvey/KinveyTests/FindOperationTest.swift index d5723dbae..57c2c2c95 100644 --- a/Kinvey/KinveyTests/FindOperationTest.swift +++ b/Kinvey/KinveyTests/FindOperationTest.swift @@ -14,7 +14,7 @@ class FindOperationTest: StoreTestCase { override func setUp() { super.setUp() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) } override func tearDown() { @@ -27,7 +27,7 @@ class FindOperationTest: StoreTestCase { weak var expectationSave = expectation(description: "Save") - store.save(person, options: Options(writePolicy: .forceLocal)) { + store.save(person, options: try! Options(writePolicy: .forceLocal)) { switch $0 { case .success(let person): XCTAssertEqual(person, self.person) @@ -54,7 +54,7 @@ class FindOperationTest: StoreTestCase { weak var expectationGet = expectation(description: "Get") let query = Query(format: "personId == %@", personId) - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let person): break @@ -83,7 +83,7 @@ class FindOperationTest: StoreTestCase { weak var expectationGet = expectation(description: "Get") let query = Query(format: "personId == %@", personId) - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 0) diff --git a/Kinvey/KinveyTests/ForgotToCallSuper.swift b/Kinvey/KinveyTests/ForgotToCallSuper.swift index 6621ba6ed..ea78b6166 100644 --- a/Kinvey/KinveyTests/ForgotToCallSuper.swift +++ b/Kinvey/KinveyTests/ForgotToCallSuper.swift @@ -87,21 +87,21 @@ class ForgotToCallSuperPersistable: Persistable { class ForgotToCallSuper: XCTestCase { func testForgotToCallSuper() { - expect { () -> Void in - let _ = ForgotToCallSuperEntity.propertyMappingReverse() - }.to(throwAssertion()) + expect { + try ForgotToCallSuperEntity.propertyMappingReverse() + }.to(throwError()) } func testForgotToCallSuper2() { - expect { () -> Void in - let _ = ForgotToCallSuperEntity2.propertyMappingReverse() - }.to(throwAssertion()) + expect { + try ForgotToCallSuperEntity2.propertyMappingReverse() + }.to(throwError()) } func testForgotToCallSuperPersistable() { - expect { () -> Void in - let _ = ForgotToCallSuperPersistable.propertyMappingReverse() - }.to(throwAssertion()) + expect { + try ForgotToCallSuperPersistable.propertyMappingReverse() + }.to(throwError()) } } diff --git a/Kinvey/KinveyTests/JsonTestCase.swift b/Kinvey/KinveyTests/JsonTestCase.swift index d11813aab..24708da3f 100644 --- a/Kinvey/KinveyTests/JsonTestCase.swift +++ b/Kinvey/KinveyTests/JsonTestCase.swift @@ -14,7 +14,7 @@ class JsonTestCase: StoreTestCase { func testFromToJson() { signUp() - let storeProject = DataStore.collection(.network, options: Options(client: client)) + let storeProject = try! DataStore.collection(.network, options: try! Options(client: client)) var project = RefProject() project.name = "Mall" @@ -63,7 +63,7 @@ class JsonTestCase: StoreTestCase { XCTAssertNotNil(project.uniqueId) XCTAssertNotEqual(project.uniqueId, "") - let storeDirectory = DataStore.collection(.network, options: Options(client: client)) + let storeDirectory = try! DataStore.collection(.network, options: try! Options(client: client)) let directory = DirectoryEntry() directory.nameFirst = "Victor" diff --git a/Kinvey/KinveyTests/KinveyTestCase.swift b/Kinvey/KinveyTests/KinveyTestCase.swift index 668cdcecc..57e6948ac 100644 --- a/Kinvey/KinveyTests/KinveyTestCase.swift +++ b/Kinvey/KinveyTests/KinveyTestCase.swift @@ -511,7 +511,7 @@ class KinveyTestCase: XCTestCase { } private func removeAll(_ type: T.Type) where T: NSObject { - let store = DataStore.collection() + let store = try! DataStore.collection() if let cache = store.cache { cache.clear(query: nil) } diff --git a/Kinvey/KinveyTests/NetworkStoreTests.swift b/Kinvey/KinveyTests/NetworkStoreTests.swift index e887c5344..69572c5dd 100644 --- a/Kinvey/KinveyTests/NetworkStoreTests.swift +++ b/Kinvey/KinveyTests/NetworkStoreTests.swift @@ -25,7 +25,7 @@ class NetworkStoreTests: StoreTestCase { super.setUp() signUp() - store = DataStore.collection() + store = try! DataStore.collection() } override func assertThread() { @@ -37,7 +37,7 @@ class NetworkStoreTests: StoreTestCase { return } - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) let event = Event() event.name = "Friday Party!" @@ -223,7 +223,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationSave = expectation(description: "Save") - store.save(person, options: Options(writePolicy: .forceNetwork)) { + store.save(person, options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success(let person): XCTAssertNotNil(person.address) @@ -291,7 +291,7 @@ class NetworkStoreTests: StoreTestCase { } } - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) weak var expectationSave = expectation(description: "Save") @@ -347,7 +347,7 @@ class NetworkStoreTests: StoreTestCase { person.address = address - let request = store.save(person, options: Options(writePolicy: .forceNetwork)) + let request = store.save(person, options: try! Options(writePolicy: .forceNetwork)) XCTAssertTrue(request.wait(timeout: defaultTimeout)) guard let result = request.result else { return @@ -396,7 +396,7 @@ class NetworkStoreTests: StoreTestCase { person.address = address - let request = store.save(person, options: Options(writePolicy: .forceNetwork)) + let request = store.save(person, options: try! Options(writePolicy: .forceNetwork)) do { let person = try request.waitForResult(timeout: defaultTimeout).value() XCTAssertNotNil(person.address) @@ -410,7 +410,7 @@ class NetworkStoreTests: StoreTestCase { } func testCount() { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) var eventsCount: Int? = nil @@ -446,7 +446,7 @@ class NetworkStoreTests: StoreTestCase { do { weak var expectationCount = expectation(description: "Count") - store.count(options: Options(readPolicy: .forceLocal)) { + store.count(options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let count): XCTAssertEqual(count, 0) @@ -538,7 +538,7 @@ class NetworkStoreTests: StoreTestCase { } func testCountSync() { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) var eventsCount: Int? = nil @@ -567,7 +567,7 @@ class NetworkStoreTests: StoreTestCase { } do { - let request = store.count(options: Options(readPolicy: .forceLocal)) + let request = store.count(options: try! Options(readPolicy: .forceLocal)) XCTAssertTrue(request.wait(timeout: defaultTimeout)) guard let result = request.result else { return @@ -647,7 +647,7 @@ class NetworkStoreTests: StoreTestCase { } func testCountTryCatchSync() { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) var eventsCount: Int? = nil @@ -672,7 +672,7 @@ class NetworkStoreTests: StoreTestCase { } do { - let request = store.count(options: Options(readPolicy: .forceLocal)) + let request = store.count(options: try! Options(readPolicy: .forceLocal)) let count = try request.waitForResult(timeout: defaultTimeout).value() XCTAssertEqual(count, 0) } catch { @@ -733,7 +733,7 @@ class NetworkStoreTests: StoreTestCase { } func testCountTranslateQuery() { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) if useMockData { mockResponse { (request) -> HttpResponse in @@ -772,7 +772,7 @@ class NetworkStoreTests: StoreTestCase { } func testCountTimeoutError() { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) mockResponse(error: timeoutError) defer { @@ -836,7 +836,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationSave = self.expectation(description: "Save") - self.store.save(person, options: Options(writePolicy: .forceNetwork)) { + self.store.save(person, options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success: break @@ -898,7 +898,7 @@ class NetworkStoreTests: StoreTestCase { $0.ascending("name") } - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, limit) @@ -1000,7 +1000,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find("sample-id", options: Options(readPolicy: .forceNetwork)) { + store.find("sample-id", options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -1036,7 +1036,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationSave = expectation(description: "Save") - store.save(person, options: Options(writePolicy: .forceNetwork)) { + store.save(person, options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -1076,7 +1076,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -1107,7 +1107,7 @@ class NetworkStoreTests: StoreTestCase { setURLProtocol(nil) } - let request = store.find(options: Options(readPolicy: .forceNetwork)) + let request = store.find(options: try! Options(readPolicy: .forceNetwork)) XCTAssertTrue(request.wait(timeout: defaultTimeout)) guard let result = request.result else { return @@ -1136,7 +1136,7 @@ class NetworkStoreTests: StoreTestCase { setURLProtocol(nil) } - let request = store.find(options: Options(readPolicy: .forceNetwork)) + let request = store.find(options: try! Options(readPolicy: .forceNetwork)) do { let _ = try request.waitForResult(timeout: defaultTimeout).value() XCTFail() @@ -1170,7 +1170,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find("id-not-found", options: Options(readPolicy: .forceNetwork)) { + store.find("id-not-found", options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -1209,7 +1209,7 @@ class NetworkStoreTests: StoreTestCase { setURLProtocol(nil) } - let request = store.find("id-not-found", options: Options(readPolicy: .forceNetwork)) + let request = store.find("id-not-found", options: try! Options(readPolicy: .forceNetwork)) XCTAssertTrue(request.wait(timeout: defaultTimeout)) guard let result = request.result else { return @@ -1245,7 +1245,7 @@ class NetworkStoreTests: StoreTestCase { setURLProtocol(nil) } - let request = store.find("id-not-found", options: Options(readPolicy: .forceNetwork)) + let request = store.find("id-not-found", options: try! Options(readPolicy: .forceNetwork)) do { let _ = try request.waitForResult(timeout: defaultTimeout).value() XCTFail() @@ -1276,20 +1276,23 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) store.find(options: nil) { (result: Result, Swift.Error>) in switch result { - case .success(let results): - XCTAssertEqual(results.count, 1) - expect { () -> Void in - for _ in results { - XCTFail() - } - XCTFail() - }.to(throwAssertion()) + case .success: + XCTFail() case .failure(let error): - XCTFail(error.localizedDescription) + let error = error as? Kinvey.Error + XCTAssertNotNil(error) + if let error = error { + switch error { + case .invalidOperation(let description): + XCTAssertEqual(description, "_id is required: \(Person.self)\n[\"name\": Victor]") + default: + XCTFail(error.localizedDescription) + } + } } expectationFind?.fulfill() } @@ -1311,7 +1314,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - let store = DataStore.collection(.network, validationStrategy: .randomSample(percentage: 0.1)) + let store = try! DataStore.collection(.network, validationStrategy: .randomSample(percentage: 0.1)) store.find(options: nil) { (result: Result, Swift.Error>) in switch result { @@ -1350,7 +1353,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - let store = DataStore.collection(.network, validationStrategy: .all) + let store = try! DataStore.collection(.network, validationStrategy: .all) store.find(options: nil) { (result: Result, Swift.Error>) in switch result { @@ -1390,7 +1393,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - let store = DataStore.collection(.network, validationStrategy: .all) + let store = try! DataStore.collection(.network, validationStrategy: .all) store.find(options: nil) { (result: Result, Swift.Error>) in switch result { @@ -1420,7 +1423,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - let store = DataStore.collection(.network, validationStrategy: .randomSample(percentage: 0)) + let store = try! DataStore.collection(.network, validationStrategy: .randomSample(percentage: 0)) store.find(options: nil) { (result: Result, Swift.Error>) in switch result { @@ -1453,7 +1456,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - let store = DataStore.collection(.network, validationStrategy: .custom(validationBlock: { (entity: Array>) in + let store = try! DataStore.collection(.network, validationStrategy: .custom(validationBlock: { (entity: Array>) in })) store.find(options: nil) { (result: Result, Swift.Error>) in @@ -1483,7 +1486,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find("sample-id", options: Options(readPolicy: .forceNetwork)) { + store.find("sample-id", options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -1516,7 +1519,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationRemove = expectation(description: "Remove") - store.remove(byId: "sample-id", options: Options(writePolicy: .forceNetwork)) { + store.remove(byId: "sample-id", options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -1547,7 +1550,7 @@ class NetworkStoreTests: StoreTestCase { setURLProtocol(nil) } - let request = store.remove(byId: "sample-id", options: Options(writePolicy: .forceNetwork)) + let request = store.remove(byId: "sample-id", options: try! Options(writePolicy: .forceNetwork)) XCTAssertTrue(request.wait(timeout: defaultTimeout)) guard let result = request.result else { return @@ -1576,7 +1579,7 @@ class NetworkStoreTests: StoreTestCase { setURLProtocol(nil) } - let request = store.remove(byId: "sample-id", options: Options(writePolicy: .forceNetwork)) + let request = store.remove(byId: "sample-id", options: try! Options(writePolicy: .forceNetwork)) do { let _ = try request.waitForResult(timeout: defaultTimeout).value() XCTFail() @@ -1603,7 +1606,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationRemove = expectation(description: "Remove") - store.remove(options: Options(writePolicy: .forceNetwork)) { + store.remove(options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -1666,7 +1669,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 2) @@ -1693,7 +1696,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationRemove = expectation(description: "Remove") - store.remove(persons, options: Options(writePolicy: .forceNetwork)) { + store.remove(persons, options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -1758,7 +1761,7 @@ class NetworkStoreTests: StoreTestCase { setURLProtocol(nil) } - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) weak var expectationFind = expectation(description: "Find") @@ -1845,7 +1848,7 @@ class NetworkStoreTests: StoreTestCase { setURLProtocol(nil) } - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) weak var expectationFind = expectation(description: "Find") @@ -1916,7 +1919,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 2) @@ -1943,7 +1946,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationRemove = expectation(description: "Remove") - store.remove(byIds: persons.map { $0.entityId! }, options: Options(writePolicy: .forceNetwork)) { + store.remove(byIds: persons.map { $0.entityId! }, options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success(let count): XCTAssertEqual(count, persons.count) @@ -1998,7 +2001,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 2) @@ -2025,7 +2028,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationRemove = expectation(description: "Remove") - store.remove(byIds: persons.map { $0.entityId! }, options: Options(writePolicy: .forceNetwork)) { + store.remove(byIds: persons.map { $0.entityId! }, options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -2050,7 +2053,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationRemove = expectation(description: "Remove") - store.remove(byIds: [], options: Options(writePolicy: .forceNetwork)) { + store.remove(byIds: [], options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success: XCTFail() @@ -2087,7 +2090,7 @@ class NetworkStoreTests: StoreTestCase { } } - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) weak var expectationRemove = expectation(description: "Remove") @@ -2114,7 +2117,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationRemove = expectation(description: "Remove") - store.removeAll(options: Options(writePolicy: .forceNetwork)) { + store.removeAll(options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success: break @@ -2134,7 +2137,7 @@ class NetworkStoreTests: StoreTestCase { let person = Person() person.name = "Test" - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) weak var expectationSave = expectation(description: "Save") @@ -2153,12 +2156,12 @@ class NetworkStoreTests: StoreTestCase { expectationSave = nil } - XCTAssertEqual(DataStore.collection(.network).syncCount(), 0) - XCTAssertEqual(DataStore.collection(.sync).syncCount(), 1) + XCTAssertEqual(try! DataStore.collection(.network).syncCount(), 0) + XCTAssertEqual(try! DataStore.collection(.sync).syncCount(), 1) DataStore.clearCache() - XCTAssertEqual(DataStore.collection(.sync).syncCount(), 0) + XCTAssertEqual(try! DataStore.collection(.sync).syncCount(), 0) } func testClientAppVersion() { @@ -2173,7 +2176,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") store.find( - options: Options( + options: try! Options( readPolicy: .forceNetwork, clientAppVersion: "1.0.0" ) @@ -2205,7 +2208,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") store.find( - options: Options( + options: try! Options( readPolicy: .forceNetwork, customRequestProperties: [ "someKey" : "someValue" @@ -2238,7 +2241,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - let options = Options( + let options = try! Options( readPolicy: .forceNetwork, customRequestProperties: [ "someKeyPerRequest" : "someValuePerRequest" @@ -2324,7 +2327,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in + store.find(options: try! Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in switch result { case .success(let results): XCTAssertEqual(results.count, 0) @@ -2363,7 +2366,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationSave = expectation(description: "Save") - store.save(person, options: Options(writePolicy: .forceNetwork)) { + store.save(person, options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success(let _person): person = _person @@ -2402,7 +2405,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertGreaterThan(persons.count, 0) @@ -2461,7 +2464,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationSave = expectation(description: "Save") - store.save(person, options: Options(writePolicy: .forceNetwork)) { + store.save(person, options: try! Options(writePolicy: .forceNetwork)) { switch $0 { case .success(let _person): person = _person @@ -2496,7 +2499,7 @@ class NetworkStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(personId, options: Options(readPolicy: .forceNetwork)) { + store.find(personId, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let person): XCTAssertNotNil(person.geolocation) @@ -2554,7 +2557,7 @@ class NetworkStoreTests: StoreTestCase { do { weak var expectationQuery = expectation(description: "Query") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertNotNil(persons.first) @@ -2580,7 +2583,7 @@ class NetworkStoreTests: StoreTestCase { do { weak var expectationQuery = expectation(description: "Query") - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertNotNil(persons.first) @@ -2610,7 +2613,7 @@ class NetworkStoreTests: StoreTestCase { do { weak var expectationQuery = expectation(description: "Query") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertNil(persons.first) @@ -2629,7 +2632,7 @@ class NetworkStoreTests: StoreTestCase { do { weak var expectationQuery = expectation(description: "Query") - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertNil(persons.first) @@ -2703,7 +2706,7 @@ class NetworkStoreTests: StoreTestCase { do { weak var expectationQuery = expectation(description: "Query") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertNotNil(persons.first) @@ -2729,7 +2732,7 @@ class NetworkStoreTests: StoreTestCase { do { weak var expectationQuery = expectation(description: "Query") - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertNotNil(persons.first) @@ -2767,7 +2770,7 @@ class NetworkStoreTests: StoreTestCase { do { weak var expectationQuery = expectation(description: "Query") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let persons): XCTAssertNil(persons.first) @@ -2786,7 +2789,7 @@ class NetworkStoreTests: StoreTestCase { do { weak var expectationQuery = expectation(description: "Query") - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertNil(persons.first) @@ -2807,7 +2810,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupCustomAggregation() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) if useMockData { mockResponse(json: [ @@ -2849,7 +2852,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupCustomAggregationSync() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) if useMockData { mockResponse(json: [ @@ -2886,7 +2889,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupCustomAggregationTryCatchSync() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) if useMockData { mockResponse(json: [ @@ -2919,7 +2922,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupCustomAggregationByName() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) if useMockData { mockResponse(json: [ @@ -2965,7 +2968,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupCustomAggregationTimeoutError() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) mockResponse(error: timeoutError) defer { @@ -2997,7 +3000,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupAggregationCountByName() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) if useMockData { mockResponse(json: [ @@ -3043,7 +3046,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupAggregationCountByNameTimeoutError() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) mockResponse(error: timeoutError) defer { @@ -3075,7 +3078,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupAggregationSumByName() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) if useMockData { mockResponse(json: [ @@ -3122,7 +3125,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupAggregationSumByNameTimeoutError() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) mockResponse(error: timeoutError) defer { @@ -3155,7 +3158,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupAggregationAvgByName() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) if useMockData { mockResponse(json: [ @@ -3204,7 +3207,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupAggregationAvgByNameTimeoutError() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) mockResponse(error: timeoutError) defer { @@ -3237,7 +3240,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupAggregationMinByName() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) if useMockData { mockResponse(json: [ @@ -3284,7 +3287,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupAggregationMinByNameTimeoutError() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) mockResponse(error: timeoutError) defer { @@ -3317,7 +3320,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupAggregationMaxByName() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) if useMockData { mockResponse(json: [ @@ -3364,7 +3367,7 @@ class NetworkStoreTests: StoreTestCase { func testGroupAggregationMaxByNameTimeoutError() { signUp() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) mockResponse(error: timeoutError) defer { @@ -3395,22 +3398,42 @@ class NetworkStoreTests: StoreTestCase { } func testGroupCustomResultKey() { - expect { () -> Void in - let _ = Aggregation.custom(keys: [], initialObject: [:], reduceJSFunction: "").resultKey - }.to(throwAssertion()) + expect { + try Aggregation.custom(keys: [], initialObject: [:], reduceJSFunction: "").resultKey() + }.to(throwError()) } func testRemoveByEmptyId() { - let store = DataStore.collection(.network) - expect { () -> Void in - store.remove(byId: "") { _ in + let store = try! DataStore.collection(.network) + + weak var expectationRemove = expectation(description: "Remove") + + store.remove(byId: "") { + switch $0 { + case .success: XCTFail() + case .failure(let error): + let error = error as? Kinvey.Error + XCTAssertNotNil(error) + if let error = error { + switch error { + case .invalidOperation(let description): + XCTAssertEqual(description, "id cannot be an empty string") + default: + XCTFail(error.localizedDescription) + } + } } - }.to(throwAssertion()) + expectationRemove?.fulfill() + } + + waitForExpectations(timeout: defaultTimeout) { error in + expectationRemove = nil + } } func testAutoPaginationDisabled() { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) mockResponse( statusCode: 400, @@ -3487,7 +3510,7 @@ class NetworkStoreTests: StoreTestCase { setURLProtocol(nil) } - let store = DataStore.collection(.network, autoPagination: true) + let store = try! DataStore.collection(.network, autoPagination: true) weak var expectationFind = expectation(description: "Find") @@ -3549,11 +3572,11 @@ class NetworkStoreTests: StoreTestCase { setURLProtocol(nil) } - let store = DataStore.collection(.sync, autoPagination: true) + let store = try! DataStore.collection(.sync, autoPagination: true) weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork, maxSizePerResultSet: pageSizeLimit)) { (result: Result, Swift.Error>) in + store.find(options: try! Options(readPolicy: .forceNetwork, maxSizePerResultSet: pageSizeLimit)) { (result: Result, Swift.Error>) in switch result { case .success(let products): XCTAssertEqual(products.count, expectedCount) @@ -3638,12 +3661,12 @@ class NetworkStoreTests: StoreTestCase { nextEdition.retailPrice = 40 book.nextEdition = nextEdition - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) do { weak var expectationFind = expectation(description: "Find") - store.find(Query(format: "title == %@", book.title!), options: Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in + store.find(Query(format: "title == %@", book.title!), options: try! Options(readPolicy: .forceNetwork)) { (result: Result, Swift.Error>) in switch result { case .success(let books): XCTAssertEqual(books.count, 1) @@ -3714,8 +3737,8 @@ class NetworkStoreTests: StoreTestCase { } func testDataStoreCacheInstances() { - let ds1 = DataStore.collection(.network, options: Options(deltaSet: true)) - let ds2 = DataStore.collection(.network, options: Options(deltaSet: false)) + let ds1 = try! DataStore.collection(.network, options: try! Options(deltaSet: true)) + let ds2 = try! DataStore.collection(.network, options: try! Options(deltaSet: false)) XCTAssertTrue(ds1.deltaSet) XCTAssertFalse(ds2.deltaSet) @@ -3727,7 +3750,7 @@ class NetworkStoreTests: StoreTestCase { func testFindCancel() { signUp() - let dataStore = DataStore.collection(.network) + let dataStore = try! DataStore.collection(.network) var running = true @@ -3781,7 +3804,7 @@ class NetworkStoreTests: StoreTestCase { setURLProtocol(nil) } - let dataStore = DataStore.collection(.network) + let dataStore = try! DataStore.collection(.network) weak var expectationFind = expectation(description: "Find") diff --git a/Kinvey/KinveyTests/NoCacheTestCase.swift b/Kinvey/KinveyTests/NoCacheTestCase.swift index e9b244a83..e34f0a2e7 100644 --- a/Kinvey/KinveyTests/NoCacheTestCase.swift +++ b/Kinvey/KinveyTests/NoCacheTestCase.swift @@ -44,7 +44,7 @@ class NoCacheTestCase: XCTestCase { } } - let dataStore = DataStore.collection(.network) + let dataStore = try! DataStore.collection(.network) mockResponse(json: [ [ diff --git a/Kinvey/KinveyTests/PerformanceProductTestCase.swift b/Kinvey/KinveyTests/PerformanceProductTestCase.swift index 142829580..67fee1e31 100644 --- a/Kinvey/KinveyTests/PerformanceProductTestCase.swift +++ b/Kinvey/KinveyTests/PerformanceProductTestCase.swift @@ -164,7 +164,7 @@ class PerformanceProductTestCase: KinveyTestCase { lazy var count: Int? = { var count: Int? - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) weak var expectationCount = self.expectation(description: "Count") @@ -262,7 +262,7 @@ class PerformanceProductTestCase: KinveyTestCase { XCTAssertNotNil(count) - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) self.measure { let query = Query() @@ -299,7 +299,7 @@ class PerformanceProductTestCase: KinveyTestCase { let count = self.productsJsonArray!.count var checkpoint = Date() - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) for productJson in self.productsJsonArray![skip ..< count] { if let product = Product(JSON: productJson) { @@ -343,7 +343,7 @@ class PerformanceProductTestCase: KinveyTestCase { func testPerformanceConsideringNetworkLatency() { XCTAssertNotNil(count) - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) self.measure { let query = Query() @@ -378,7 +378,7 @@ class PerformanceProductTestCase: KinveyTestCase { // TODO: change after https://kinvey.atlassian.net/browse/BACK-2315 gets solved query.limit = 10000 - 1 - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) self.measure { weak var expectationFind = self.expectation(description: "Find") @@ -409,7 +409,7 @@ class PerformanceProductTestCase: KinveyTestCase { // TODO: change after https://kinvey.atlassian.net/browse/BACK-2315 gets solved query.limit = 10000 - 1 - let store = DataStore.collection(.cache) + let store = try! DataStore.collection(.cache) self.measure { weak var expectationFindLocal = self.expectation(description: "Find Local") @@ -449,13 +449,13 @@ class PerformanceProductTestCase: KinveyTestCase { // TODO: change after https://kinvey.atlassian.net/browse/BACK-2315 gets solved query.limit = 10000 - 1 - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) for _ in 1 ... 10 { weak var expectationFindLocal = self.expectation(description: "Find Local") weak var expectationFindNetwork = self.expectation(description: "Find Network") - store.find(query, options: Options(readPolicy: .both)) { + store.find(query, options: try! Options(readPolicy: .both)) { switch $0 { case .success(let products): if expectationFindLocal == nil { @@ -514,12 +514,12 @@ class PerformanceProductTestCase: KinveyTestCase { // TODO: change after https://kinvey.atlassian.net/browse/BACK-2315 gets solved query.limit = 10000 - 1 - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) self.measure { weak var expectationFind = self.expectation(description: "Find") - store.find(query, options: Options(deltaSet: true)) { + store.find(query, options: try! Options(deltaSet: true)) { switch $0 { case .success(let products): break @@ -565,7 +565,7 @@ class PerformanceProductTestCase: KinveyTestCase { query.skip = 0 query.limit = 10000 - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) self.measure { weak var expectationFind = self.expectation(description: "Find") @@ -594,7 +594,7 @@ class PerformanceProductTestCase: KinveyTestCase { loadMockData() - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) var skip = 0 let limit = 100 @@ -647,7 +647,7 @@ class PerformanceProductTestCase: KinveyTestCase { loadMockData() - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) var skip = 0 let limit = 1000 diff --git a/Kinvey/KinveyTests/PerformanceTestCase.swift b/Kinvey/KinveyTests/PerformanceTestCase.swift index b38364648..1016cb5d5 100644 --- a/Kinvey/KinveyTests/PerformanceTestCase.swift +++ b/Kinvey/KinveyTests/PerformanceTestCase.swift @@ -17,7 +17,7 @@ class PerformanceTestCase: StoreTestCase { XCTAssertNotNil(client.activeUser) if let user = client.activeUser { - store = DataStore.collection(.sync) + store = try! DataStore.collection(.sync) let n = 1000 @@ -42,12 +42,12 @@ class PerformanceTestCase: StoreTestCase { expectationPush = nil } - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", user.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", user.userId) self.measure { weak var expectationFind = self.expectation(description: "Find") - self.store.find(query, options: Options(deltaSet: false)) { + self.store.find(query, options: try! Options(deltaSet: false)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, n) @@ -71,7 +71,7 @@ class PerformanceTestCase: StoreTestCase { XCTAssertNotNil(client.activeUser) if let user = client.activeUser { - store = DataStore.collection(.sync) + store = try! DataStore.collection(.sync) let n = 10000 @@ -96,12 +96,12 @@ class PerformanceTestCase: StoreTestCase { expectationPush = nil } - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", user.userId) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", user.userId) self.measure { weak var expectationFind = self.expectation(description: "Find") - self.store.find(query, options: Options(deltaSet: false)) { + self.store.find(query, options: try! Options(deltaSet: false)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, n) diff --git a/Kinvey/KinveyTests/PersistableTestCase.swift b/Kinvey/KinveyTests/PersistableTestCase.swift index 8193f1ff0..9f98f35c1 100644 --- a/Kinvey/KinveyTests/PersistableTestCase.swift +++ b/Kinvey/KinveyTests/PersistableTestCase.swift @@ -12,7 +12,7 @@ import XCTest class PersistableTestCase: StoreTestCase { func testAclNull() { - store = DataStore.collection() + store = try! DataStore.collection() class NullAclURLProtocol : URLProtocol { @@ -54,7 +54,7 @@ class PersistableTestCase: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 1) @@ -71,7 +71,7 @@ class PersistableTestCase: StoreTestCase { } func testAclEmpty() { - store = DataStore.collection() + store = try! DataStore.collection() class NullAclURLProtocol : URLProtocol { @@ -114,7 +114,7 @@ class PersistableTestCase: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 1) @@ -131,7 +131,7 @@ class PersistableTestCase: StoreTestCase { } func testKmdNull() { - store = DataStore.collection() + store = try! DataStore.collection() class NullAclURLProtocol : URLProtocol { @@ -172,7 +172,7 @@ class PersistableTestCase: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 1) @@ -189,7 +189,7 @@ class PersistableTestCase: StoreTestCase { } func testKmdEmpty() { - store = DataStore.collection() + store = try! DataStore.collection() class NullAclURLProtocol : URLProtocol { @@ -231,7 +231,7 @@ class PersistableTestCase: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(options: Options(readPolicy: .forceNetwork)) { + store.find(options: try! Options(readPolicy: .forceNetwork)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 1) diff --git a/Kinvey/KinveyTests/QueryTest.swift b/Kinvey/KinveyTests/QueryTest.swift index 99a013bce..6f9009324 100644 --- a/Kinvey/KinveyTests/QueryTest.swift +++ b/Kinvey/KinveyTests/QueryTest.swift @@ -74,7 +74,7 @@ class QueryTest: XCTestCase { setURLProtocol(nil) } - let dataStore = DataStore.collection(.network, options: Options(client: client)) + let dataStore = try! DataStore.collection(.network, options: try! Options(client: client)) let query = Query(format: "obj._id == %@", 30) weak var expectationFind = expectation(description: "Find") @@ -348,37 +348,37 @@ class QueryTest: XCTestCase { } func testArrayContains() { - let cache = RealmCache(persistenceId: "_kid_", schemaVersion: 0) + let cache = try! RealmCache(persistenceId: "_kid_", schemaVersion: 0) let predicate = cache.translate(predicate: NSPredicate(format: "authorNames contains %@", "Victor")) XCTAssertEqual(predicate, NSPredicate(format: "SUBQUERY(authorNames, $item, $item.value == %@).@count > 0", "Victor")) } func testArrayIndex() { - let cache = RealmCache(persistenceId: "_kid_", schemaVersion: 0) + let cache = try! RealmCache(persistenceId: "_kid_", schemaVersion: 0) let predicate = cache.translate(predicate: NSPredicate(format: "authorNames[0] == %@", "Victor")) XCTAssertEqual(predicate, NSPredicate(format: "authorNames[0].value == %@", "Victor")) } func testArrayFirst() { - let cache = RealmCache(persistenceId: "_kid_", schemaVersion: 0) + let cache = try! RealmCache(persistenceId: "_kid_", schemaVersion: 0) let predicate = cache.translate(predicate: NSPredicate(format: "authorNames[first] == %@", "Victor")) XCTAssertEqual(predicate, NSPredicate(format: "authorNames[first].value == %@", "Victor")) } func testArrayLast() { - let cache = RealmCache(persistenceId: "_kid_", schemaVersion: 0) + let cache = try! RealmCache(persistenceId: "_kid_", schemaVersion: 0) let predicate = cache.translate(predicate: NSPredicate(format: "authorNames[last] == %@", "Victor")) XCTAssertEqual(predicate, NSPredicate(format: "authorNames[last].value == %@", "Victor")) } func testArraySize() { - let cache = RealmCache(persistenceId: "_kid_", schemaVersion: 0) + let cache = try! RealmCache(persistenceId: "_kid_", schemaVersion: 0) let predicate = cache.translate(predicate: NSPredicate(format: "authorNames[size] == 2")) XCTAssertEqual(predicate, NSPredicate(format: "authorNames[size] == 2")) } func testArraySubquery() { - let cache = RealmCache(persistenceId: "_kid_", schemaVersion: 0) + let cache = try! RealmCache(persistenceId: "_kid_", schemaVersion: 0) let predicate = cache.translate(predicate: NSPredicate(format: "subquery(authorNames, $authorNames, $authorNames like[c] %@).$count > 0", "Vic*")) XCTAssertEqual(predicate, NSPredicate(format: "subquery(authorNames, $authorNames, $authorNames.value like[c] %@).$count > 0", "Vic*")) } diff --git a/Kinvey/KinveyTests/RealtimeTestCase.swift b/Kinvey/KinveyTests/RealtimeTestCase.swift index f62a4b9fe..b30e288ec 100644 --- a/Kinvey/KinveyTests/RealtimeTestCase.swift +++ b/Kinvey/KinveyTests/RealtimeTestCase.swift @@ -277,8 +277,8 @@ class RealtimeTestCase: KinveyTestCase { } if registered { - let dataStoreSync = DataStore.collection(.sync) - let dataStoreNetwork = DataStore.collection(.network) + let dataStoreSync = try! DataStore.collection(.sync) + let dataStoreNetwork = try! DataStore.collection(.network) do { weak var expectationSave = self.expectation(description: "Save") @@ -363,7 +363,7 @@ class RealtimeTestCase: KinveyTestCase { } DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) { - dataStoreNetwork.save(person, options: Options(writePolicy: nil)) { (result: Result) in + dataStoreNetwork.save(person, options: try! Options(writePolicy: nil)) { (result: Result) in switch result { case .success: break @@ -383,7 +383,7 @@ class RealtimeTestCase: KinveyTestCase { acl.readers = [user.userId] $0.acl = acl } - dataStoreNetwork.save(person2, options: Options(writePolicy: nil)) { (result: Result) in + dataStoreNetwork.save(person2, options: try! Options(writePolicy: nil)) { (result: Result) in switch result { case .success: break @@ -468,7 +468,7 @@ class RealtimeTestCase: KinveyTestCase { } func testSubscribeNoActiveUser() { - let dataStore = DataStore.collection(.sync) + let dataStore = try! DataStore.collection(.sync) weak var expectationSubscribe = self.expectation(description: "Subscribe") @@ -490,7 +490,7 @@ class RealtimeTestCase: KinveyTestCase { func testSubscribeNotRegisterForRealtime() { signUp() - let dataStore = DataStore.collection(.sync) + let dataStore = try! DataStore.collection(.sync) weak var expectationSubscribe = self.expectation(description: "Subscribe") @@ -564,7 +564,7 @@ class RealtimeTestCase: KinveyTestCase { } if registered { - let dataStore = DataStore.collection(.sync) + let dataStore = try! DataStore.collection(.sync) do { weak var expectationSubscribe = self.expectation(description: "Subscribe") @@ -674,7 +674,7 @@ class RealtimeTestCase: KinveyTestCase { } if registered { - let dataStore = DataStore.collection(.sync) + let dataStore = try! DataStore.collection(.sync) do { if useMockData { @@ -756,7 +756,7 @@ class RealtimeTestCase: KinveyTestCase { } func testUnSubscribeNoActiveUser() { - let dataStore = DataStore.collection(.sync) + let dataStore = try! DataStore.collection(.sync) weak var expectationSubscribe = self.expectation(description: "Subscribe") @@ -778,7 +778,7 @@ class RealtimeTestCase: KinveyTestCase { func testUnSubscribeNotRegisterForRealtime() { signUp() - let dataStore = DataStore.collection(.sync) + let dataStore = try! DataStore.collection(.sync) weak var expectationSubscribe = self.expectation(description: "Subscribe") @@ -927,7 +927,7 @@ class RealtimeTestCase: KinveyTestCase { let query = Query(format: "_id != %@", user.userId) query.limit = 2 - user.find(query: query, options: Options(client: client)) { + user.find(query: query, options: try! Options(client: client)) { switch $0 { case .success(let users): usersArray = users @@ -1225,7 +1225,7 @@ class RealtimeTestCase: KinveyTestCase { let query = Query(format: "_id != %@", user.userId) query.limit = 2 - user.find(query: query, options: Options(client: client)) { + user.find(query: query, options: try! Options(client: client)) { switch $0 { case .success(let users): usersArray = users @@ -1417,7 +1417,7 @@ class RealtimeTestCase: KinveyTestCase { let query = Query(format: "_id != %@", user.userId) query.limit = 2 - user.find(query: query, options: Options(client: client)) { + user.find(query: query, options: try! Options(client: client)) { switch $0 { case .success(let users): usersArray = users diff --git a/Kinvey/KinveyTests/SyncStoreTests.swift b/Kinvey/KinveyTests/SyncStoreTests.swift index f5143c342..8576ffa40 100644 --- a/Kinvey/KinveyTests/SyncStoreTests.swift +++ b/Kinvey/KinveyTests/SyncStoreTests.swift @@ -27,15 +27,15 @@ class SyncStoreTests: StoreTestCase { signUp() - store = DataStore.collection(.sync) + store = try! DataStore.collection(.sync) } var mockCount = 0 override func tearDown() { if let activeUser = client.activeUser { - let store = DataStore.collection(.network) - let query = Query(format: "\(Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) + let store = try! DataStore.collection(.network) + let query = Query(format: "\(try! Person.aclProperty() ?? Person.EntityCodingKeys.acl.rawValue).creator == %@", activeUser.userId) if useMockData { mockResponse(json: ["count" : mockCount]) @@ -383,7 +383,7 @@ class SyncStoreTests: StoreTestCase { removeFiles() XCTAssertFalse(fileManager.fileExists(atPath: customPath)) - store = DataStore.collection(.sync, tag: tag) + store = try! DataStore.collection(.sync, tag: tag) defer { removeFiles() XCTAssertFalse(fileManager.fileExists(atPath: customPath)) @@ -684,7 +684,7 @@ class SyncStoreTests: StoreTestCase { func testPurgeInvalidDataStoreType() { save() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) weak var expectationPurge = expectation(description: "Purge") @@ -900,7 +900,7 @@ class SyncStoreTests: StoreTestCase { func testSyncInvalidDataStoreType() { save() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) weak var expectationSync = expectation(description: "Sync") @@ -965,7 +965,7 @@ class SyncStoreTests: StoreTestCase { func testPush() { save() - let bookDataStore = DataStore.collection(.sync) + let bookDataStore = try! DataStore.collection(.sync) do { let book = Book() @@ -1034,7 +1034,7 @@ class SyncStoreTests: StoreTestCase { func testPushSync() { save() - let bookDataStore = DataStore.collection(.sync) + let bookDataStore = try! DataStore.collection(.sync) do { let book = Book() @@ -1101,7 +1101,7 @@ class SyncStoreTests: StoreTestCase { func testPushTryCatchSync() { save() - let bookDataStore = DataStore.collection(.sync) + let bookDataStore = try! DataStore.collection(.sync) do { let book = Book() @@ -1189,7 +1189,7 @@ class SyncStoreTests: StoreTestCase { func testPushInvalidDataStoreType() { save() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) defer { store.clearCache() } @@ -1459,7 +1459,7 @@ class SyncStoreTests: StoreTestCase { func testPullInvalidDataStoreType() { //save() - store = DataStore.collection(.network) + store = try! DataStore.collection(.network) weak var expectationPull = expectation(description: "Pull") @@ -1909,7 +1909,7 @@ class SyncStoreTests: StoreTestCase { weak var expectationGet = expectation(description: "Get") let query = Query(format: "personId == %@", personId) - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 0) @@ -1931,7 +1931,7 @@ class SyncStoreTests: StoreTestCase { weak var expectationGet = expectation(description: "Get") let query = Query(format: "personId == %@", personId) - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let persons): XCTAssertEqual(persons.count, 1) @@ -1964,7 +1964,7 @@ class SyncStoreTests: StoreTestCase { weak var expectationSave = self.expectation(description: "Save") - self.store.save(person, options: Options(writePolicy: .forceLocal)) { + self.store.save(person, options: try! Options(writePolicy: .forceLocal)) { switch $0 { case .success: break @@ -1994,7 +1994,7 @@ class SyncStoreTests: StoreTestCase { $0.ascending("name") } - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, limit) @@ -2032,7 +2032,7 @@ class SyncStoreTests: StoreTestCase { $0.ascending("name") } - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 5) @@ -2068,7 +2068,7 @@ class SyncStoreTests: StoreTestCase { $0.ascending("name") } - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 5) @@ -2105,7 +2105,7 @@ class SyncStoreTests: StoreTestCase { $0.ascending("name") } - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 4) @@ -2142,7 +2142,7 @@ class SyncStoreTests: StoreTestCase { $0.ascending("name") } - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 0) @@ -2166,7 +2166,7 @@ class SyncStoreTests: StoreTestCase { $0.ascending("name") } - store.find(query, options: Options(readPolicy: .forceLocal)) { + store.find(query, options: try! Options(readPolicy: .forceLocal)) { switch $0 { case .success(let results): XCTAssertEqual(results.count, 0) @@ -2622,7 +2622,7 @@ class SyncStoreTests: StoreTestCase { weak var expectationFind = expectation(description: "Find") - store.find(query, options: Options(readPolicy: .forceNetwork)) { + store.find(query, options: try! Options(readPolicy: .forceNetwork)) { XCTAssertTrue(Thread.isMainThread) switch $0 { case .success(let persons): @@ -2713,9 +2713,9 @@ class SyncStoreTests: StoreTestCase { } - expect { () -> Void in - let _ = RealmCache(persistenceId: UUID().uuidString, schemaVersion: 0) - }.to(throwAssertion()) + expect { + try RealmCache(persistenceId: UUID().uuidString, schemaVersion: 0) + }.to(throwError()) } func testRealmSyncNotEntity() { @@ -2755,9 +2755,9 @@ class SyncStoreTests: StoreTestCase { } - expect { () -> Void in - let _ = RealmSync(persistenceId: UUID().uuidString, schemaVersion: 0) - }.to(throwAssertion()) + expect { + try RealmSync(persistenceId: UUID().uuidString, schemaVersion: 0) + }.to(throwError()) } func testCancelLocalRequest() { @@ -2784,14 +2784,14 @@ class SyncStoreTests: StoreTestCase { } func testNewTypeDataStore() { - var store = DataStore.collection() - store = store.collection(newType: Book.self).collection(newType: Person.self) + var store = try! DataStore.collection() + store = try! store.collection(newType: Book.self).collection(newType: Person.self) } func testGroupCustomAggregationError() { signUp() - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) if useMockData { mockResponse(json: [ @@ -2838,7 +2838,7 @@ class SyncStoreTests: StoreTestCase { func testGroupCustomAggregationErrorSync() { signUp() - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) if useMockData { mockResponse(json: [ @@ -2880,7 +2880,7 @@ class SyncStoreTests: StoreTestCase { func testGroupCustomAggregationErrorTryCatchSync() { signUp() - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) if useMockData { mockResponse(json: [ @@ -2916,7 +2916,7 @@ class SyncStoreTests: StoreTestCase { } func testObjectMappingMemoryLeak() { - var store = DataStore.collection(.network) + var store = try! DataStore.collection(.network) mockResponse(json: [ [ @@ -2964,7 +2964,7 @@ class SyncStoreTests: StoreTestCase { } func testServerSideDeltaSetSyncAdd1Record() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var initialCount = 0 do { @@ -3107,7 +3107,7 @@ class SyncStoreTests: StoreTestCase { } func testServerSideDeltaSetSyncUpdate1Record() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { mockResponse { (request) -> HttpResponse in @@ -3223,7 +3223,7 @@ class SyncStoreTests: StoreTestCase { } func testServerSideDeltaSetSyncDelete1Record() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { mockResponse { (request) -> HttpResponse in @@ -3326,7 +3326,7 @@ class SyncStoreTests: StoreTestCase { } func testServerSideDeltaSetSyncAddUpdateDelete2Records() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { mockResponse { (request) -> HttpResponse in @@ -3501,7 +3501,7 @@ class SyncStoreTests: StoreTestCase { } func testServerSideDeltaSetSyncClearCacheNoQuery() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { mockResponse { (request) -> HttpResponse in @@ -3700,7 +3700,7 @@ class SyncStoreTests: StoreTestCase { } func testServerSideDeltaSetSyncClearCache() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { mockResponse { (request) -> HttpResponse in @@ -3900,7 +3900,7 @@ class SyncStoreTests: StoreTestCase { } func testServerSideDeltaSetSyncResultSetExceed() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { mockResponse { (request) -> HttpResponse in @@ -4002,7 +4002,7 @@ class SyncStoreTests: StoreTestCase { } func testServerSideDeltaSetSyncMissingConfiguration() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) mockResponse { (request) -> HttpResponse in guard let url = request.url else { @@ -4087,7 +4087,7 @@ class SyncStoreTests: StoreTestCase { } func testServerSideDeltaSetSyncParameterValueOutOfRange() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { mockResponse { (request) -> HttpResponse in @@ -4206,7 +4206,7 @@ class SyncStoreTests: StoreTestCase { } func testSyncStoreDisabledDeltasetWithPull() { - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) var initialCount = Int64(0) do { @@ -4370,7 +4370,7 @@ class SyncStoreTests: StoreTestCase { } //Create 1 person, Make regular GET, Create 1 more person, Make deltaset request func testSyncStoreDeltaset1ExtraItemAddedWithPull() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -4524,7 +4524,7 @@ class SyncStoreTests: StoreTestCase { } func testSyncStoreDeltasetSinceIsRespectedWithoutChangesWithPull() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -4653,7 +4653,7 @@ class SyncStoreTests: StoreTestCase { } //Create 2 persons, pull with regular GET, update 1, deltaset returning 1 changed, delete 1, deltaset returning 1 deleted func testSyncStoreDeltaset1ItemAdded1Updated1DeletedWithPull() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var idToUpdate = "" var idToDelete = "" @@ -4888,7 +4888,7 @@ class SyncStoreTests: StoreTestCase { } //Created 3 items, 2 of which satisfy a query, pull with query with regular GET, delete 1 item that satisfies the query, deltaset returns 1 deleted item func testSyncStoreDeltaset1WithQuery1ItemDeletedWithPull() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var idToDelete = "" var initialCount = Int64(0) @@ -5054,7 +5054,7 @@ class SyncStoreTests: StoreTestCase { //Created 3 items, 2 of which satisfy a query, pull with query with regular GET, update 1 item that satisfies the query, deltaset returns 1 changed item func testSyncStoreDeltasetWithQuery1ItemUpdatedWithPull() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var idToUpdate = "" var initialCount = Int64(0) @@ -5239,7 +5239,7 @@ class SyncStoreTests: StoreTestCase { } //Create 1 item, pull with regular GET, create another item, deltaset returns 1 changed, switch off deltaset, pull with regular GET func testSyncStoreDeltasetTurnedOffSendsRegularGETWithPull() { - var store = DataStore.collection(.sync, options: Options(deltaSet: true)) + var store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -5392,7 +5392,7 @@ class SyncStoreTests: StoreTestCase { expectationPull = nil } } - store = DataStore.collection(.sync, options: Options(deltaSet: false)) + store = try! DataStore.collection(.sync, options: try! Options(deltaSet: false)) do { if useMockData { mockResponse { (request) -> HttpResponse in @@ -5470,7 +5470,7 @@ class SyncStoreTests: StoreTestCase { func testSyncStoreDisabledDeltasetWithSync() { - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) var initialCount = 0 do { @@ -5623,7 +5623,7 @@ class SyncStoreTests: StoreTestCase { } func testSyncStoreDeltaset1ExtraItemAddedWithSync() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -5770,7 +5770,7 @@ class SyncStoreTests: StoreTestCase { } func testSyncStoreDeltasetSinceIsRespectedWithoutChangesWithSync() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -5893,7 +5893,7 @@ class SyncStoreTests: StoreTestCase { } func testSyncStoreDeltaset1ItemAdded1Updated1DeletedWithSync() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var idToUpdate = "" var idToDelete = "" @@ -6117,7 +6117,7 @@ class SyncStoreTests: StoreTestCase { } func testSyncStoreDeltaset1WithQuery1ItemDeletedWithSync() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var idToDelete = "" var initialCount = Int64(0) @@ -6275,7 +6275,7 @@ class SyncStoreTests: StoreTestCase { } func testSyncStoreDeltasetWithQuery1ItemUpdatedWithSync() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var idToUpdate = "" var initialCount = Int64(0) @@ -6455,7 +6455,7 @@ class SyncStoreTests: StoreTestCase { } func testSyncStoreDeltasetTurnedOffSendsRegularGETWithSync() { - var store = DataStore.collection(.sync, options: Options(deltaSet: true)) + var store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var initialCount = Int64(0) do { @@ -6601,7 +6601,7 @@ class SyncStoreTests: StoreTestCase { expectationSync = nil } } - store = DataStore.collection(.sync, options: Options(deltaSet: false)) + store = try! DataStore.collection(.sync, options: try! Options(deltaSet: false)) do { if useMockData { mockResponse { (request) -> HttpResponse in @@ -6675,7 +6675,7 @@ class SyncStoreTests: StoreTestCase { } func testSyncStoreDeltaset1ItemAdded1Updated1DeletedWithFindNetworkReadPolicy() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var idToUpdate = "" var idToDelete = "" @@ -6748,7 +6748,7 @@ class SyncStoreTests: StoreTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -6828,7 +6828,7 @@ class SyncStoreTests: StoreTestCase { } } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -6893,7 +6893,7 @@ class SyncStoreTests: StoreTestCase { } } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query() store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -6924,7 +6924,7 @@ class SyncStoreTests: StoreTestCase { } func testSyncStoreDeltaset1WithQuery1ItemDeletedWithFindWithNetworkPolicy() { - let store = DataStore.collection(.sync, options: Options(deltaSet: true)) + let store = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) var idToDelete = "" var initialCount = Int64(0) @@ -7002,7 +7002,7 @@ class SyncStoreTests: StoreTestCase { } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query(format: "age == %@", 23) store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -7068,7 +7068,7 @@ class SyncStoreTests: StoreTestCase { } } weak var expectationFind = expectation(description: "Find") - var options = Options() + var options = try! Options() options.readPolicy = .forceNetwork var query = Query(format: "age == %@", 23) store.find(query, options: options) { (result: Result, Swift.Error>) in @@ -7133,7 +7133,7 @@ class SyncStoreTests: StoreTestCase { setURLProtocol(nil) } - let store = DataStore.collection(.sync, autoPagination: true) + let store = try! DataStore.collection(.sync, autoPagination: true) let startMemory = reportMemory() XCTAssertNotNil(startMemory) @@ -7162,7 +7162,7 @@ class SyncStoreTests: StoreTestCase { } func testObjectObserve() { - let dataStore = DataStore.collection(.sync) + let dataStore = try! DataStore.collection(.sync) let personId = UUID().uuidString @@ -7215,7 +7215,7 @@ class SyncStoreTests: StoreTestCase { } func testCollectionObserve() { - let dataStore = DataStore.collection(.sync) + let dataStore = try! DataStore.collection(.sync) let personId = UUID().uuidString let personName = "Victor" @@ -7322,7 +7322,7 @@ class SyncStoreTests: StoreTestCase { setURLProtocol(nil) } - let dataStore = DataStore.collection(.sync, options: Options(deltaSet: true)) + let dataStore = try! DataStore.collection(.sync, options: try! Options(deltaSet: true)) do { var results = try dataStore.pull(options: nil).waitForResult(timeout: defaultTimeout).value() diff --git a/Kinvey/KinveyTests/UserTests.swift b/Kinvey/KinveyTests/UserTests.swift index 7da9e18df..858a4fdca 100644 --- a/Kinvey/KinveyTests/UserTests.swift +++ b/Kinvey/KinveyTests/UserTests.swift @@ -182,7 +182,7 @@ class UserTests: KinveyTestCase { if let user = client.activeUser { weak var expectationDestroyUser = expectation(description: "Destroy User") - User.destroy(userId: user.userId, options: Options(client: client)) { + User.destroy(userId: user.userId, options: try! Options(client: client)) { XCTAssertTrue(Thread.isMainThread) switch $0 { @@ -218,7 +218,7 @@ class UserTests: KinveyTestCase { weak var expectationDestroyUser = expectation(description: "Destroy User") - User.destroy(userId: user.userId, hard: true, options: Options(client: client)) { + User.destroy(userId: user.userId, hard: true, options: try! Options(client: client)) { XCTAssertTrue(Thread.isMainThread) switch $0 { @@ -254,7 +254,7 @@ class UserTests: KinveyTestCase { weak var expectationDestroyUser = expectation(description: "Destroy User") - User.destroy(userId: user.userId, hard: false, options: Options(client: client)) { + User.destroy(userId: user.userId, hard: false, options: try! Options(client: client)) { XCTAssertTrue(Thread.isMainThread) switch $0 { @@ -290,7 +290,7 @@ class UserTests: KinveyTestCase { weak var expectationDestroyUser = expectation(description: "Destroy User") - User.destroy(userId: user.userId, hard: true, options: Options(client: client)) { + User.destroy(userId: user.userId, hard: true, options: try! Options(client: client)) { XCTAssertTrue(Thread.isMainThread) switch $0 { @@ -321,7 +321,7 @@ class UserTests: KinveyTestCase { if let user = client.activeUser { weak var expectationDestroyUser = expectation(description: "Destroy User") - User.destroy(userId: user.userId, options: Options(client: client)) { + User.destroy(userId: user.userId, options: try! Options(client: client)) { XCTAssertTrue(Thread.isMainThread) switch $0 { @@ -385,7 +385,7 @@ class UserTests: KinveyTestCase { return } - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) do { if useMockData { @@ -502,7 +502,7 @@ class UserTests: KinveyTestCase { return } - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) do { if useMockData { @@ -768,12 +768,12 @@ class UserTests: KinveyTestCase { } } - let dataStore = DataStore.collection(.network) + let dataStore = try! DataStore.collection(.network) weak var expectationFind = expectation(description: "Find") dataStore.find( - options: Options( + options: try! Options( client: client ) ) { @@ -2538,7 +2538,7 @@ class UserTests: KinveyTestCase { XCTAssertNotNil(Kinvey.sharedClient.activeUser) if Kinvey.sharedClient.activeUser != nil { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) weak var expectationFind = expectation(description: "Find") @@ -2763,7 +2763,7 @@ class UserTests: KinveyTestCase { XCTAssertNotNil(client.activeUser) do { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) weak var expectationFind = expectation(description: "Find") @@ -2992,7 +2992,7 @@ class UserTests: KinveyTestCase { XCTAssertNotNil(client.activeUser) do { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) weak var expectationFind = expectation(description: "Find") @@ -3171,7 +3171,7 @@ class UserTests: KinveyTestCase { XCTAssertNotNil(client.activeUser) do { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) weak var expectationFind = expectation(description: "Find") @@ -3278,7 +3278,7 @@ class UserTests: KinveyTestCase { XCTAssertNotNil(Kinvey.sharedClient.activeUser) do { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) weak var expectationFind = expectation(description: "Find") @@ -3353,7 +3353,7 @@ class UserTests: KinveyTestCase { MIC.login( redirectURI: URL(string: "myCustomURIScheme://")!, code: "1234", - options: Options( + options: try! Options( authServiceId: nil ) ) { result in @@ -3413,7 +3413,7 @@ class UserTests: KinveyTestCase { MIC.login( redirectURI: URL(string: "myCustomURIScheme://")!, code: "1234", - options: Options( + options: try! Options( authServiceId: nil ) ) { result in @@ -3448,7 +3448,7 @@ class UserTests: KinveyTestCase { redirectURI: URL(string: "myCustomURIScheme://")!, username: UUID().uuidString, password: UUID().uuidString, - options: Options( + options: try! Options( authServiceId: nil ) ) { result in @@ -3525,7 +3525,7 @@ class UserTests: KinveyTestCase { redirectURI: URL(string: "myCustomURIScheme://")!, username: UUID().uuidString, password: UUID().uuidString, - options: Options( + options: try! Options( authServiceId: nil ) ) { result in @@ -3585,7 +3585,7 @@ class UserTests: KinveyTestCase { redirectURI: URL(string: "myCustomURIScheme://")!, username: UUID().uuidString, password: UUID().uuidString, - options: Options( + options: try! Options( authServiceId: nil ) ) { result in @@ -3645,7 +3645,7 @@ class UserTests: KinveyTestCase { redirectURI: URL(string: "myCustomURIScheme://")!, username: UUID().uuidString, password: UUID().uuidString, - options: Options( + options: try! Options( authServiceId: nil ) ) { result in @@ -4058,7 +4058,7 @@ extension UserTests { XCTAssertTrue(wait(toBeTrue: self.client.activeUser != nil)) do { - let store = DataStore.collection(.network) + let store = try! DataStore.collection(.network) weak var expectationFind = expectation(description: "Find") @@ -4303,7 +4303,7 @@ extension UserTests { let redirectURI = URL(string: "throwAnError://")! - User.presentMICViewController(redirectURI: redirectURI, micUserInterface: .uiWebView, options: Options(timeout: 60)) { + User.presentMICViewController(redirectURI: redirectURI, micUserInterface: .uiWebView, options: try! Options(timeout: 60)) { XCTAssertTrue(Thread.isMainThread) switch $0 { case .success: @@ -4347,7 +4347,7 @@ extension UserTests { weak var expectationLogin = expectation(description: "Login") let redirectURI = URL(string: "throwAnError://")! - User.presentMICViewController(redirectURI: redirectURI, micUserInterface: .wkWebView, options: Options(timeout: 60)) { + User.presentMICViewController(redirectURI: redirectURI, micUserInterface: .wkWebView, options: try! Options(timeout: 60)) { XCTAssertTrue(Thread.isMainThread) switch $0 { case .success: @@ -4419,7 +4419,7 @@ extension UserTests { let result = User.login( redirectURI: URL(string: "myCustomURIScheme://")!, micURL: URL(string: "myCustomURIScheme://?code=1234")!, - options: Options(client: client) + options: try! Options(client: client) ) XCTAssertTrue(result) @@ -4431,7 +4431,7 @@ extension UserTests { let result = User.login( redirectURI: URL(string: "myCustomURIScheme://")!, micURL: URL(string: "myCustomURIScheme://?no_code=1234")!, - options: Options(client: client) + options: try! Options(client: client) ) XCTAssertFalse(result) } @@ -4491,7 +4491,7 @@ extension UserTests { let result = User.login( redirectURI: URL(string: "myCustomURIScheme://")!, micURL: URL(string: "myCustomURIScheme://?code=1234")!, - options: Options(client: client) + options: try! Options(client: client) ) XCTAssertTrue(result) @@ -4569,7 +4569,7 @@ extension UserTests { let result = User.login( redirectURI: URL(string: "myCustomURIScheme://")!, micURL: URL(string: "myCustomURIScheme://?code=1234")!, - options: Options(client: client) + options: try! Options(client: client) ) XCTAssertTrue(result) @@ -4579,8 +4579,8 @@ extension UserTests { func testUserMicViewControllerCoding() { expect { () -> Void in - let _ = Kinvey.MICLoginViewController(coder: NSKeyedArchiver()) - }.to(throwAssertion()) + Kinvey.MICLoginViewController(coder: NSKeyedArchiver()) + }.to(raiseException()) } func testMICTimeoutAction() { @@ -4598,7 +4598,7 @@ extension UserTests { User.presentMICViewController( redirectURI: redirectURI, micUserInterface: .uiWebView, - options: Options(timeout: 3) + options: try! Options(timeout: 3) ) { XCTAssertTrue(Thread.isMainThread) switch $0 { @@ -4642,7 +4642,7 @@ extension UserTests { User.presentMICViewController( redirectURI: redirectURI, micUserInterface: .uiWebView, - options: Options(timeout: 60) + options: try! Options(timeout: 60) ) { XCTAssertTrue(Thread.isMainThread) switch $0 { @@ -4773,7 +4773,7 @@ extension UserTests { XCTAssertNotNil(Kinvey.sharedClient.activeUser) - let store = DataStore.collection(.sync) + let store = try! DataStore.collection(.sync) do { mockResponse(json: [ diff --git a/Kinvey/RealtimeSender/ViewController.swift b/Kinvey/RealtimeSender/ViewController.swift index 83ddc1ee6..1af9f0a71 100644 --- a/Kinvey/RealtimeSender/ViewController.swift +++ b/Kinvey/RealtimeSender/ViewController.swift @@ -162,7 +162,7 @@ class ViewController: NSViewController { User.login( username: username!, password: password!, - options: Options(client: sharedClient) + options: try! Options(client: sharedClient) ) { switch $0 { case .success(let user): diff --git a/Kinvey/SSOApp/SSOApp1/AppDelegate.swift b/Kinvey/SSOApp/SSOApp1/AppDelegate.swift index d753f701e..5e079aa22 100644 --- a/Kinvey/SSOApp/SSOApp1/AppDelegate.swift +++ b/Kinvey/SSOApp/SSOApp1/AppDelegate.swift @@ -51,7 +51,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { } func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { - if User.login(redirectURI: micRedirectURI, micURL: url, options: Options(authServiceId: authServiceId)) { + if User.login(redirectURI: micRedirectURI, micURL: url, options: try! Options(authServiceId: authServiceId)) { return true }