diff --git a/Sources/MeiliSearch/Async/Client+async.swift b/Sources/MeiliSearch/Async/Client+async.swift new file mode 100644 index 00000000..4448a39f --- /dev/null +++ b/Sources/MeiliSearch/Async/Client+async.swift @@ -0,0 +1,235 @@ +import Foundation + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension MeiliSearch { + /** + See `createIndex(uid:primaryKey:_:)` + */ + public func createIndex(uid: String, primaryKey: String? = nil) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.createIndex(uid: uid, primaryKey: primaryKey) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getIndex(_:_:)` + */ + public func getIndex(_ uid: String) async throws -> Index { + try await withCheckedThrowingContinuation { continuation in + self.getIndex(uid) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getIndexes(params:_:)` + */ + public func getIndexes(params: IndexesQuery? = nil) async throws -> IndexesResults { + try await withCheckedThrowingContinuation { continuation in + self.getIndexes(params: params) { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateIndex(uid:primaryKey:_:)` + */ + public func updateIndex(uid: String, primaryKey: String) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateIndex(uid: uid, primaryKey: primaryKey) { result in + continuation.resume(with: result) + } + } + } + + /** + See `deleteIndex(_:_:)` + */ + public func deleteIndex(_ uid: String) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.deleteIndex(uid) { result in + continuation.resume(with: result) + } + } + } + + /** + See `waitForTask(taskUid:options:_:)` + */ + public func waitForTask(taskUid: Int, options: WaitOptions? = nil) async throws -> Task { + try await withCheckedThrowingContinuation { continuation in + self.waitForTask(taskUid: taskUid, options: options) { result in + continuation.resume(with: result) + } + } + } + + /** + See `waitForTask(task:options:_:)` + */ + public func waitForTask(task: TaskInfo, options: WaitOptions? = nil) async throws -> Task { + try await withCheckedThrowingContinuation { continuation in + self.waitForTask(task: task, options: options) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getTask(taskUid:_:)` + */ + public func getTask(taskUid: Int) async throws -> Task { + try await withCheckedThrowingContinuation { continuation in + self.getTask(taskUid: taskUid) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getTasks(params:_:)` + */ + public func getTasks(params: TasksQuery? = nil) async throws -> TasksResults { + try await withCheckedThrowingContinuation { continuation in + self.getTasks(params: params) { result in + continuation.resume(with: result) + } + } + } + + /** + See `cancelTasks(filter:completion:)` + */ + public func cancelTasks(filter: CancelTasksQuery) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.cancelTasks(filter: filter) { result in + continuation.resume(with: result) + } + } + } + + /** + See `deleteTasks(filter:completion:)` + */ + public func deleteTasks(filter: DeleteTasksQuery) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.deleteTasks(filter: filter) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getKeys(params:_:)` + */ + public func getKeys(params: KeysQuery? = nil) async throws -> KeysResults { + try await withCheckedThrowingContinuation { continuation in + self.getKeys(params: params) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getKey(keyOrUid:_:)` + */ + public func getKey(keyOrUid: String) async throws -> Key { + try await withCheckedThrowingContinuation { continuation in + self.getKey(keyOrUid: keyOrUid) { result in + continuation.resume(with: result) + } + } + } + + /** + See `createKey(_:_:)` + */ + public func createKey(_ keyParams: KeyParams) async throws -> Key { + try await withCheckedThrowingContinuation { continuation in + self.createKey(keyParams) { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateKey(keyOrUid:keyParams:_:)` + */ + public func updateKey(keyOrUid: String, keyParams: KeyUpdateParams) async throws -> Key { + try await withCheckedThrowingContinuation { continuation in + self.updateKey(keyOrUid: keyOrUid, keyParams: keyParams) { result in + continuation.resume(with: result) + } + } + } + + /** + See `deleteKey(keyOrUid:_:)` + */ + public func deleteKey(keyOrUid: String) async throws { + try await withCheckedThrowingContinuation { continuation in + self.deleteKey(keyOrUid: keyOrUid) { result in + continuation.resume(with: result) + } + } + } + + /** + See `allStats(_:)` + */ + public func allStats() async throws -> AllStats { + try await withCheckedThrowingContinuation { continuation in + self.allStats { result in + continuation.resume(with: result) + } + } + } + + /** + See `health(_:)` + */ + public func health() async throws -> Health { + try await withCheckedThrowingContinuation { continuation in + self.health { result in + continuation.resume(with: result) + } + } + } + + /** + See `isHealthy(_:)` + */ + public func isHealthy() async -> Bool { + await withCheckedContinuation { continuation in + self.isHealthy { result in + continuation.resume(returning: result) + } + } + } + + /** + See `version(_:)` + */ + public func version() async throws -> Version { + try await withCheckedThrowingContinuation { continuation in + self.version { result in + continuation.resume(with: result) + } + } + } + + /** + See `createDump(_:)` + */ + public func createDump() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.createDump { result in + continuation.resume(with: result) + } + } + } +} diff --git a/Sources/MeiliSearch/Async/Indexes+async.swift b/Sources/MeiliSearch/Async/Indexes+async.swift index 13757d7a..91c3691e 100644 --- a/Sources/MeiliSearch/Async/Indexes+async.swift +++ b/Sources/MeiliSearch/Async/Indexes+async.swift @@ -3,15 +3,649 @@ import Foundation @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Indexes { /** - Search in the index. - - - Parameter searchParameters: Options on search. - - Throws: Error if a failure occurred. - - Returns: On completion if the request was successful a `Searchable` instance is returned containing the values. + See `get(_:)` + */ + public func get() async throws -> Index { + try await withCheckedThrowingContinuation { continuation in + self.get { result in + continuation.resume(with: result) + } + } + } + + /** + See `update(primaryKey:_:)` + */ + public func update(primaryKey: String) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.update(primaryKey: primaryKey) { result in + continuation.resume(with: result) + } + } + } + + /** + See `delete(_:)` + */ + public func delete() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.delete { result in + continuation.resume(with: result) + } + } + } + + /** + See `addDocuments(documents:encoder:primaryKey:_:)` + */ + public func addDocuments(documents: [T], encoder: JSONEncoder? = nil, primaryKey: String? = nil) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.addDocuments(documents: documents, encoder: encoder, primaryKey: primaryKey) { result in + continuation.resume(with: result) + } + } + } + + /** + See `addDocuments(documents:primaryKey:_:)` + */ + public func addDocuments(documents: Data, primaryKey: String? = nil) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.addDocuments(documents: documents, primaryKey: primaryKey) { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateDocuments(documents:encoder:primaryKey:_:)` + */ + public func updateDocuments(documents: [T], encoder: JSONEncoder? = nil, primaryKey: String? = nil) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateDocuments(documents: documents, encoder: encoder, primaryKey: primaryKey) { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateDocuments(documents:primaryKey:_:)` + */ + public func updateDocuments(documents: Data, primaryKey: String? = nil) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateDocuments(documents: documents, primaryKey: primaryKey) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getDocument(_:fields:_:)` + */ + public func getDocument(_ identifier: String, fields: [String]? = nil) async throws -> T { + try await withCheckedThrowingContinuation { continuation in + self.getDocument(identifier, fields: fields) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getDocument(_:fields:_:)` + */ + public func getDocument(_ identifier: Int, fields: [String]? = nil) async throws -> T { + try await withCheckedThrowingContinuation { continuation in + self.getDocument(identifier, fields: fields) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getDocuments(params:_:)` + */ + public func getDocuments(params: DocumentsQuery? = nil) async throws -> DocumentsResults { + try await withCheckedThrowingContinuation { continuation in + self.getDocuments(params: params) { result in + continuation.resume(with: result) + } + } + } + + /** + See `deleteDocument(_:_:)` + */ + public func deleteDocument(_ documentId: String) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.deleteDocument(documentId) { result in + continuation.resume(with: result) + } + } + } + + /** + See `deleteAllDocuments(_:)` + */ + public func deleteAllDocuments() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.deleteAllDocuments { result in + continuation.resume(with: result) + } + } + } + + /** + See `deleteBatchDocuments(_:_:)` + */ + public func deleteBatchDocuments(_ documentIds: [String]) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.deleteBatchDocuments(documentIds) { result in + continuation.resume(with: result) + } + } + } + + /** + See `search(_:_:)` */ public func search(_ searchParameters: SearchParameters) async throws -> Searchable { try await withCheckedThrowingContinuation { continuation in - self.search.search(self.uid, searchParameters) { result in + self.search(searchParameters) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getTask(taskUid:_:)` + */ + public func getTask(taskUid: Int) async throws -> Task { + try await withCheckedThrowingContinuation { continuation in + self.getTask(taskUid: taskUid) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getTasks(params:_:)` + */ + public func getTasks(params: TasksQuery? = nil) async throws -> TasksResults { + try await withCheckedThrowingContinuation { continuation in + self.getTasks(params: params) { result in + continuation.resume(with: result) + } + } + } + + /** + See `getSettings(_:)` + */ + public func getSettings() async throws -> SettingResult { + try await withCheckedThrowingContinuation { continuation in + self.getSettings { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateSettings(_:_:)` + */ + public func updateSettings(_ setting: Setting) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateSettings(setting) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetSettings(_:)` + */ + public func resetSettings() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetSettings { result in + continuation.resume(with: result) + } + } + } + + /** + See `getSynonyms(_:)` + */ + public func getSynonyms() async throws -> [String: [String]] { + try await withCheckedThrowingContinuation { continuation in + self.getSynonyms { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateSynonyms(_:_:)` + */ + public func updateSynonyms(_ synonyms: [String: [String]]?) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateSynonyms(synonyms) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetSynonyms(_:)` + */ + public func resetSynonyms() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetSynonyms { result in + continuation.resume(with: result) + } + } + } + + /** + See `getStopWords(_:)` + */ + public func getStopWords() async throws -> [String] { + try await withCheckedThrowingContinuation { continuation in + self.getStopWords { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateStopWords(_:_:)` + */ + public func updateStopWords(_ stopWords: [String]?) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateStopWords(stopWords) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetStopWords(_:)` + */ + public func resetStopWords() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetStopWords { result in + continuation.resume(with: result) + } + } + } + + /** + See `getRankingRules(_:)` + */ + public func getRankingRules() async throws -> [String] { + try await withCheckedThrowingContinuation { continuation in + self.getRankingRules { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateRankingRules(_:_:)` + */ + public func updateRankingRules(_ rankingRules: [String]) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateRankingRules(rankingRules) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetRankingRules(_:)` + */ + public func resetRankingRules() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetRankingRules { result in + continuation.resume(with: result) + } + } + } + + /** + See `getDistinctAttribute(_:)` + */ + public func getDistinctAttribute() async throws -> String? { + try await withCheckedThrowingContinuation { continuation in + self.getDistinctAttribute { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateDistinctAttribute(_:_:)` + */ + public func updateDistinctAttribute(_ distinctAttribute: String) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateDistinctAttribute(distinctAttribute) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetDistinctAttribute(_:)` + */ + public func resetDistinctAttribute() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetDistinctAttribute { result in + continuation.resume(with: result) + } + } + } + + /** + See `getSearchableAttributes(_:)` + */ + public func getSearchableAttributes() async throws -> [String] { + try await withCheckedThrowingContinuation { continuation in + self.getSearchableAttributes { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateSearchableAttributes(_:_:)` + */ + public func updateSearchableAttributes(_ searchableAttribute: [String]) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateSearchableAttributes(searchableAttribute) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetSearchableAttributes(_:)` + */ + public func resetSearchableAttributes() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetSearchableAttributes { result in + continuation.resume(with: result) + } + } + } + + /** + See `getDisplayedAttributes(_:)` + */ + public func getDisplayedAttributes() async throws -> [String] { + try await withCheckedThrowingContinuation { continuation in + self.getDisplayedAttributes { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateDisplayedAttributes(_:_:)` + */ + public func updateDisplayedAttributes(_ displayedAttribute: [String]) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateDisplayedAttributes(displayedAttribute) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetDisplayedAttributes(_:)` + */ + public func resetDisplayedAttributes() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetDisplayedAttributes { result in + continuation.resume(with: result) + } + } + } + + /** + See `getFilterableAttributes(_:)` + */ + public func getFilterableAttributes() async throws -> [String] { + try await withCheckedThrowingContinuation { continuation in + self.getFilterableAttributes { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateFilterableAttributes(_:_:)` + */ + public func updateFilterableAttributes(_ attributes: [String]) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateFilterableAttributes(attributes) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetFilterableAttributes(_:)` + */ + public func resetFilterableAttributes() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetFilterableAttributes { result in + continuation.resume(with: result) + } + } + } + + /** + See `getSortableAttributes(_:)` + */ + public func getSortableAttributes() async throws -> [String] { + try await withCheckedThrowingContinuation { continuation in + self.getSortableAttributes { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateSortableAttributes(_:_:)` + */ + public func updateSortableAttributes(_ attributes: [String]) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateSortableAttributes(attributes) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetSortableAttributes(_:)` + */ + public func resetSortableAttributes() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetSortableAttributes { result in + continuation.resume(with: result) + } + } + } + + /** + See `getSeparatorTokens(_:)` + */ + public func getSeparatorTokens() async throws -> [String] { + try await withCheckedThrowingContinuation { continuation in + self.getSeparatorTokens { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateSeparatorTokens(_:_:)` + */ + public func updateSeparatorTokens(_ attributes: [String]) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateSeparatorTokens(attributes) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetSeparatorTokens(_:)` + */ + public func resetSeparatorTokens() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetSeparatorTokens { result in + continuation.resume(with: result) + } + } + } + + /** + See `getNonSeparatorTokens(_:)` + */ + public func getNonSeparatorTokens() async throws -> [String] { + try await withCheckedThrowingContinuation { continuation in + self.getNonSeparatorTokens { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateNonSeparatorTokens(_:_:)` + */ + public func updateNonSeparatorTokens(_ attributes: [String]) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateNonSeparatorTokens(attributes) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetNonSeparatorTokens(_:)` + */ + public func resetNonSeparatorTokens() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetNonSeparatorTokens { result in + continuation.resume(with: result) + } + } + } + + /** + See `getDictionary(_:)` + */ + public func getDictionary() async throws -> [String] { + try await withCheckedThrowingContinuation { continuation in + self.getDictionary { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateDictionary(_:_:)` + */ + public func updateDictionary(_ attributes: [String]) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateDictionary(attributes) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetDictionary(_:)` + */ + public func resetDictionary() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetDictionary { result in + continuation.resume(with: result) + } + } + } + + /** + See `getPaginationSettings(_:)` + */ + public func getPaginationSettings() async throws -> Pagination { + try await withCheckedThrowingContinuation { continuation in + self.getPaginationSettings { result in + continuation.resume(with: result) + } + } + } + + /** + See `updatePaginationSettings(_:_:)` + */ + public func updatePaginationSettings(_ settings: Pagination) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updatePaginationSettings(settings) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetPaginationSettings(_:)` + */ + public func resetPaginationSettings() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetPaginationSettings { result in + continuation.resume(with: result) + } + } + } + + /** + See `getTypoTolerance(_:)` + */ + public func getTypoTolerance() async throws -> TypoToleranceResult { + try await withCheckedThrowingContinuation { continuation in + self.getTypoTolerance { result in + continuation.resume(with: result) + } + } + } + + /** + See `updateTypoTolerance(_:_:)` + */ + public func updateTypoTolerance(_ typoTolerance: TypoTolerance) async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.updateTypoTolerance(typoTolerance) { result in + continuation.resume(with: result) + } + } + } + + /** + See `resetTypoTolerance(_:)` + */ + public func resetTypoTolerance() async throws -> TaskInfo { + try await withCheckedThrowingContinuation { continuation in + self.resetTypoTolerance { result in + continuation.resume(with: result) + } + } + } + + /** + See `stats(_:)` + */ + public func stats() async throws -> Stat { + try await withCheckedThrowingContinuation { continuation in + self.stats { result in continuation.resume(with: result) } } diff --git a/Sources/MeiliSearch/Indexes.swift b/Sources/MeiliSearch/Indexes.swift index 3a2c6d9d..ac958c81 100755 --- a/Sources/MeiliSearch/Indexes.swift +++ b/Sources/MeiliSearch/Indexes.swift @@ -26,7 +26,7 @@ public struct Indexes { private let documents: Documents // Search methods - internal let search: Search + private let search: Search // Settings methods private let settings: Settings diff --git a/Tests/MeiliSearchUnitTests/ClientTests.swift b/Tests/MeiliSearchUnitTests/ClientTests.swift index 66d87836..d392d84c 100644 --- a/Tests/MeiliSearchUnitTests/ClientTests.swift +++ b/Tests/MeiliSearchUnitTests/ClientTests.swift @@ -1,7 +1,6 @@ @testable import MeiliSearch import XCTest -// swiftlint:disable force_cast class ClientTests: XCTestCase { private let session = MockURLSession() private let validHost = "http://localhost:7700" @@ -91,4 +90,3 @@ class ClientTests: XCTestCase { req.put(api: "/", "{}".data(using: .utf8) ?? Data(), requiredDataResponseHandler) } } -// swiftlint:enable force_cast diff --git a/Tests/MeiliSearchUnitTests/DocumentsTests.swift b/Tests/MeiliSearchUnitTests/DocumentsTests.swift index 0526b5e0..730a774f 100755 --- a/Tests/MeiliSearchUnitTests/DocumentsTests.swift +++ b/Tests/MeiliSearchUnitTests/DocumentsTests.swift @@ -5,9 +5,6 @@ import Foundation import FoundationNetworking #endif -// swiftlint:disable force_unwrapping - -// swiftlint:disable line_length private struct Movie: Codable, Equatable { let id: Int let title: String @@ -34,15 +31,13 @@ class DocumentsTests: XCTestCase { index = self.client.index(self.uid) } - func testAddDocuments() throws { + func testAddDocuments() async throws { let jsonString = """ {"taskUid":0,"indexUid":"books_test","status":"enqueued","type":"documentAdditionOrUpdate","enqueuedAt":"2022-07-21T21:47:50.565717794Z"} """ // Prepare the mock server - let decoder = Constants.customJSONDecoder - let jsonData = jsonString.data(using: .utf8)! - let stubTask: TaskInfo = try decoder.decode(TaskInfo.self, from: jsonData) + let stubTask: TaskInfo = try decodeJSON(from: jsonString) session.pushData(jsonString, code: 202) // Start the test with the mocked server @@ -50,34 +45,20 @@ class DocumentsTests: XCTestCase { id: 287947, title: "Shazam", overview: "A boy is given the ability to become an adult superhero in times of need with a single magic word.", - releaseDate: Date(timeIntervalSince1970: TimeInterval(1553299200))) - - let expectation = XCTestExpectation(description: "Add or replace Movies document") - self.index.addDocuments( - documents: [movie], - primaryKey: "id" - ) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask.taskUid, update.taskUid) - case .failure: - XCTFail("Failed to add or replace Movies document") - } - expectation.fulfill() - } + releaseDate: Date(timeIntervalSince1970: TimeInterval(1553299200)) + ) - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.addDocuments(documents: [movie], primaryKey: "id") + XCTAssertEqual(stubTask.taskUid, update.taskUid) } - func testAddDataDocuments() throws { + func testAddDataDocuments() async throws { let jsonString = """ {"taskUid":0,"indexUid":"books_test","status":"enqueued","type":"documentAdditionOrUpdate","enqueuedAt":"2022-07-21T21:47:50.565717794Z"} """ // Prepare the mock server - let decoder = Constants.customJSONDecoder - let jsonData = jsonString.data(using: .utf8)! - let stubTask: TaskInfo = try decoder.decode(TaskInfo.self, from: jsonData) + let stubTask: TaskInfo = try decodeJSON(from: jsonString) session.pushData(jsonString, code: 202) let documentJsonString = """ @@ -91,36 +72,20 @@ class DocumentsTests: XCTestCase { """ let primaryKey: String = "" - let documents: Data = documentJsonString.data(using: .utf8)! + let documents: Data = Data(documentJsonString.utf8) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Add or replace Movies document") - - self.index.addDocuments( - documents: documents, - primaryKey: primaryKey - ) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to add or replace Movies document") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.addDocuments(documents: documents, primaryKey: primaryKey) + XCTAssertEqual(stubTask, update) } - func testUpdateDataDocuments() throws { + func testUpdateDataDocuments() async throws { let jsonString = """ {"taskUid":0,"indexUid":"books_test","status":"enqueued","type":"documentAdditionOrUpdate","enqueuedAt":"2022-07-21T21:47:50.565717794Z"} """ // Prepare the mock server - let decoder = Constants.customJSONDecoder - let jsonData = jsonString.data(using: .utf8)! - let stubTask: TaskInfo = try decoder.decode(TaskInfo.self, from: jsonData) + let stubTask: TaskInfo = try decodeJSON(from: jsonString) session.pushData(jsonString, code: 202) let documentJsonString = """ [{ @@ -130,34 +95,20 @@ class DocumentsTests: XCTestCase { """ let primaryKey: String = "movieskud" - let JsonDocuments: Data = documentJsonString.data(using: .utf8)! + let JsonDocuments: Data = Data(documentJsonString.utf8) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Add or update Movies document") - self.index.updateDocuments( - documents: JsonDocuments, - primaryKey: primaryKey) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to add or update Movies document") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateDocuments(documents: JsonDocuments, primaryKey: primaryKey) + XCTAssertEqual(stubTask, update) } - func testUpdateDocuments() throws { + func testUpdateDocuments() async throws { let jsonString = """ {"taskUid":0,"indexUid":"books_test","status":"enqueued","type":"documentAdditionOrUpdate","enqueuedAt":"2022-07-21T21:47:50.565717794Z"} """ // Prepare the mock server - let decoder = Constants.customJSONDecoder - let jsonData = jsonString.data(using: .utf8)! - let stubTask: TaskInfo = try decoder.decode(TaskInfo.self, from: jsonData) + let stubTask: TaskInfo = try decodeJSON(from: jsonString) session.pushData(jsonString, code: 202) let movie = Movie( @@ -168,24 +119,11 @@ class DocumentsTests: XCTestCase { ) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "add or update Movies document") - self.index.updateDocuments( - documents: [movie], - primaryKey: "id" - ) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to add or update Movies document") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateDocuments(documents: [movie], primaryKey: "id") + XCTAssertEqual(stubTask, update) } - func testGetDocument() throws { + func testGetDocument() async throws { let jsonString = """ { "id": 25684, @@ -198,29 +136,15 @@ class DocumentsTests: XCTestCase { // Prepare the mock server session.pushData(jsonString, code: 200) - let decoder = Constants.customJSONDecoder - decoder.dateDecodingStrategy = .formatted(Formatter.iso8601) - let data = jsonString.data(using: .utf8)! - let stubMovie: Movie = try decoder.decode(Movie.self, from: data) + let stubMovie: Movie = try decodeJSON(from: jsonString) let identifier: String = "25684" // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get Movies document") - - self.index.getDocument(identifier) { (result: Result) in - switch result { - case .success(let movie): - XCTAssertEqual(stubMovie, movie) - case .failure: - XCTFail("Failed to get Movies document") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let movie: Movie = try await self.index.getDocument(identifier) + XCTAssertEqual(stubMovie, movie) } - func testGetDocumentWithSparseFieldsets() { + func testGetDocumentWithSparseFieldsets() async throws { let jsonString = """ { "id": 25684, @@ -231,33 +155,17 @@ class DocumentsTests: XCTestCase { // Prepare the mock server session.pushData(jsonString, code: 200) - do { - let decoder = Constants.customJSONDecoder - decoder.dateDecodingStrategy = .formatted(Formatter.iso8601) - let data = jsonString.data(using: .utf8)! - let stubMovie: Movie = try decoder.decode(Movie.self, from: data) - let identifier: String = "25684" - - // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get Movies document") - - self.index.getDocument(identifier, fields: ["title", "id"]) { (result: Result) in - switch result { - case .success(let movie): - XCTAssertEqual(self.session.nextDataTask.request?.url?.query, "fields=title,id") - - XCTAssertEqual(stubMovie, movie) - case .failure: - XCTFail("Failed to get Movies document") - } - expectation.fulfill() - } - } catch { - XCTFail("Failed to parse document") - } + let stubMovie: Movie = try decodeJSON(from: jsonString) + let identifier: String = "25684" + + // Start the test with the mocked server + let movie: Movie = try await self.index.getDocument(identifier, fields: ["title", "id"]) + XCTAssertEqual(self.session.nextDataTask.request?.url?.query, "fields=title,id") + + XCTAssertEqual(stubMovie, movie) } - func testGetDocumentsWithParameters() { + func testGetDocumentsWithParameters() async throws { let jsonString = """ { "results": [], @@ -271,25 +179,11 @@ class DocumentsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get documents with parameters") - - self.index.getDocuments(params: DocumentsQuery(limit: 2, offset: 10)) { (result: Result, Swift.Error>) in - switch result { - case .success: - XCTAssertEqual(self.session.nextDataTask.request?.url?.query, "limit=2&offset=10") - - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to get all Indexes") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let _: DocumentsResults = try await self.index.getDocuments(params: DocumentsQuery(limit: 2, offset: 10)) + XCTAssertEqual(self.session.nextDataTask.request?.url?.query, "limit=2&offset=10") } - func testGetDocuments() throws { + func testGetDocuments() async throws { let jsonString = """ { "results": [ @@ -316,105 +210,55 @@ class DocumentsTests: XCTestCase { // Prepare the mock server session.pushData(jsonString, code: 200) - let decoder = Constants.customJSONDecoder - decoder.dateDecodingStrategy = .formatted(Formatter.iso8601) - let data = jsonString.data(using: .utf8)! - let stubMovies: DocumentsResults = try decoder.decode(DocumentsResults.self, from: data) + let stubMovies: DocumentsResults = try decodeJSON(from: jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get Movies documents") - - self.index.getDocuments { (result: Result, Swift.Error>) in - switch result { - case .success(let movies): - XCTAssertEqual(stubMovies, movies) - case .failure: - XCTFail("Failed to get Movies documents") - } - expectation.fulfill() - } - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let movies: DocumentsResults = try await self.index.getDocuments() + XCTAssertEqual(stubMovies, movies) } - func testDeleteDocument() throws { + func testDeleteDocument() async throws { let jsonString = """ {"taskUid":0,"indexUid":"books_test","status":"enqueued","type":"documentAdditionOrUpdate","enqueuedAt":"2022-07-21T21:47:50.565717794Z"} """ // Prepare the mock server - let decoder = Constants.customJSONDecoder - let jsonData = jsonString.data(using: .utf8)! - let stubTask: TaskInfo = try decoder.decode(TaskInfo.self, from: jsonData) + let stubTask: TaskInfo = try decodeJSON(from: jsonString) session.pushData(jsonString, code: 202) let identifier: String = "25684" // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Delete Movies document") - - self.index.deleteDocument(identifier) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to delete Movies document") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.deleteDocument(identifier) + XCTAssertEqual(stubTask, update) } - func testDeleteAllDocuments() throws { + func testDeleteAllDocuments() async throws { let jsonString = """ {"taskUid":0,"indexUid":"books_test","status":"enqueued","type":"documentAdditionOrUpdate","enqueuedAt":"2022-07-21T21:47:50.565717794Z"} """ // Prepare the mock server - let decoder = Constants.customJSONDecoder - let jsonData = jsonString.data(using: .utf8)! - let stubTask: TaskInfo = try decoder.decode(TaskInfo.self, from: jsonData) + let stubTask: TaskInfo = try decodeJSON(from: jsonString) session.pushData(jsonString, code: 202) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Delete all Movies documents") - self.index.deleteAllDocuments { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to delete all Movies documents") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.deleteAllDocuments() + XCTAssertEqual(stubTask, update) } - func testDeleteBatchDocuments() throws { + func testDeleteBatchDocuments() async throws { let jsonString = """ {"taskUid":0,"indexUid":"books_test","status":"enqueued","type":"documentAdditionOrUpdate","enqueuedAt":"2022-07-21T21:47:50.565717794Z"} """ // Prepare the mock server - let decoder = Constants.customJSONDecoder - let jsonData = jsonString.data(using: .utf8)! - let stubTask: TaskInfo = try decoder.decode(TaskInfo.self, from: jsonData) + let stubTask: TaskInfo = try decodeJSON(from: jsonString) session.pushData(jsonString, code: 202) let documentsIdentifiers: [String] = ["23488", "153738", "437035", "363869"] // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Delete all Movies documents") - self.index.deleteBatchDocuments(documentsIdentifiers) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to delete all Movies documents") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.deleteBatchDocuments(documentsIdentifiers) + XCTAssertEqual(stubTask, update) } @available(*, deprecated, message: "Testing deprecated methods - marked deprecated to avoid additional warnings below.") @@ -424,9 +268,7 @@ class DocumentsTests: XCTestCase { """ // Prepare the mock server - let decoder = Constants.customJSONDecoder - let jsonData = jsonString.data(using: .utf8)! - let stubTask: TaskInfo = try decoder.decode(TaskInfo.self, from: jsonData) + let stubTask: TaskInfo = try decodeJSON(from: jsonString) session.pushData(jsonString, code: 202) let documentsIdentifiers: [Int] = [23488, 153738, 437035, 363869] @@ -445,7 +287,3 @@ class DocumentsTests: XCTestCase { self.wait(for: [expectation], timeout: TESTS_TIME_OUT) } } -// swiftlint:enable force_unwrapping -// swiftlint:enable force_cast - -// swiftlint:enable line_length diff --git a/Tests/MeiliSearchUnitTests/DumpsTests.swift b/Tests/MeiliSearchUnitTests/DumpsTests.swift index f2d27660..8f047ad9 100644 --- a/Tests/MeiliSearchUnitTests/DumpsTests.swift +++ b/Tests/MeiliSearchUnitTests/DumpsTests.swift @@ -1,8 +1,6 @@ @testable import MeiliSearch import XCTest -// swiftlint:disable force_unwrapping - class DumpsTests: XCTestCase { private var client: MeiliSearch! private let session = MockURLSession() @@ -12,34 +10,18 @@ class DumpsTests: XCTestCase { client = try MeiliSearch(host: "http://localhost:7700", apiKey: "masterKey", session: session) } - func testCreateDump() throws { + func testCreateDump() async throws { // Prepare the mock server let json = """ { "taskUid": 278, "indexUid": null, "status": "enqueued", "type": "dumpCreation", "enqueuedAt": "2022-07-21T21:43:12.419917471Z" } """ - let data = json.data(using: .utf8)! - - let stubDump: TaskInfo = try Constants.customJSONDecoder.decode(TaskInfo.self, from: data) - + let stubDump: TaskInfo = try decodeJSON(from: json) session.pushData(json) // Start the test with the mocked server - - let expectation = XCTestExpectation(description: "Create dump") - - self.client.createDump { result in - switch result { - case .success(let dump): - XCTAssertEqual(stubDump, dump) - expectation.fulfill() - case .failure: - XCTFail("Failed to create dump") - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let dump = try await self.client.createDump() + XCTAssertEqual(stubDump, dump) } } -// swiftlint:enable force_unwrapping diff --git a/Tests/MeiliSearchUnitTests/IndexesTests.swift b/Tests/MeiliSearchUnitTests/IndexesTests.swift index a2ea1133..85dc8cbb 100755 --- a/Tests/MeiliSearchUnitTests/IndexesTests.swift +++ b/Tests/MeiliSearchUnitTests/IndexesTests.swift @@ -13,7 +13,7 @@ class IndexesTests: XCTestCase { index = client.index(self.uid) } - func testCreateIndex() { + func testCreateIndex() async throws { let jsonString = """ { "taskUid": 0, @@ -28,23 +28,11 @@ class IndexesTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Create index") - - self.client.createIndex(uid: self.uid) { result in - switch result { - case .success(let task): - XCTAssertEqual(0, task.taskUid) - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to create index") - expectation.fulfill() - } - } - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let task = try await self.client.createIndex(uid: self.uid) + XCTAssertEqual(0, task.taskUid) } - func testGetIndexWithClient() { + func testGetIndexWithClient() async throws { let jsonString = """ { "name":"Movies", @@ -59,24 +47,11 @@ class IndexesTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get index with client instance") - - self.client.getIndex(uid) { result in - switch result { - case .success(let index): - XCTAssertEqual(self.uid, index.uid) - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to get Movies index") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let index = try await self.client.getIndex(uid) + XCTAssertEqual(self.uid, index.uid) } - func testGetIndex() { + func testGetIndex() async throws { let jsonString = """ { "name":"Movies", @@ -91,24 +66,11 @@ class IndexesTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get index") - - self.index.get { result in - switch result { - case .success(let index): - XCTAssertEqual(self.uid, index.uid) - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to get Movies index") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let index = try await self.index.get() + XCTAssertEqual(self.uid, index.uid) } - func testGetIndexes() { + func testGetIndexes() async throws { let jsonString = """ { "results": [ @@ -129,25 +91,11 @@ class IndexesTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - - let expectation = XCTestExpectation(description: "Get indexes") - - self.client.getIndexes { result in - switch result { - case .success(let indexes): - XCTAssertEqual("movies", indexes.results[0].uid) - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to get all Indexes") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let indexes = try await self.client.getIndexes() + XCTAssertEqual("movies", indexes.results[0].uid) } - func testUpdateIndexWithClient() { + func testUpdateIndexWithClient() async throws { let jsonString = """ {"taskUid":0,"indexUid":"books","status":"enqueued","type":"indexUpdate","enqueuedAt":"2022-07-21T22:03:40.482534429Z"} """ @@ -157,24 +105,11 @@ class IndexesTests: XCTestCase { let primaryKey: String = "movie_review_id" // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update Movies index") - - self.client.updateIndex(uid: self.uid, primaryKey: primaryKey) { result in - switch result { - case .success(let task): - XCTAssertEqual(0, task.taskUid) - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to update Movies index") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let task = try await self.client.updateIndex(uid: self.uid, primaryKey: primaryKey) + XCTAssertEqual(0, task.taskUid) } - func testUpdateIndex() { + func testUpdateIndex() async throws { let jsonString = """ {"taskUid":0,"indexUid":"books","status":"enqueued","type":"indexUpdate","enqueuedAt":"2022-07-21T22:03:40.482534429Z"} """ @@ -184,24 +119,11 @@ class IndexesTests: XCTestCase { let primaryKey: String = "movie_review_id" // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update Movies index") - - self.index.update(primaryKey: primaryKey) { result in - switch result { - case .success(let task): - XCTAssertEqual(0, task.taskUid) - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to update Movies index") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let task = try await self.index.update(primaryKey: primaryKey) + XCTAssertEqual(0, task.taskUid) } - func testGetIndexesWithParameters() { + func testGetIndexesWithParameters() async throws { let jsonString = """ { "results": [], @@ -215,25 +137,11 @@ class IndexesTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get indexes with parameters") - - self.client.getIndexes(params: IndexesQuery(limit: 9, offset: 1)) { result in - switch result { - case .success: - XCTAssertEqual(self.session.nextDataTask.request?.url?.query, "limit=9&offset=1") - - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to get all Indexes") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + _ = try await self.client.getIndexes(params: IndexesQuery(limit: 9, offset: 1)) + XCTAssertEqual(self.session.nextDataTask.request?.url?.query, "limit=9&offset=1") } - func testGetTasksWithParametersFromIndex() { + func testGetTasksWithParametersFromIndex() async throws { let jsonString = """ { "results": [], @@ -248,26 +156,12 @@ class IndexesTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get keys with parameters") - - self.index.getTasks(params: TasksQuery(limit: 20, from: 5, next: 98, types: [.indexCreation])) { result in - switch result { - case .success: - let requestQuery = self.session.nextDataTask.request?.url?.query - - XCTAssertEqual(requestQuery, "from=5&indexUids=\(self.uid)&limit=20&next=98&types=indexCreation") - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to get all Indexes") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + _ = try await self.index.getTasks(params: TasksQuery(limit: 20, from: 5, next: 98, types: [.indexCreation])) + let requestQuery = self.session.nextDataTask.request?.url?.query + XCTAssertEqual(requestQuery, "from=5&indexUids=\(self.uid)&limit=20&next=98&types=indexCreation") } - func testDeleteIndexWithClient() { + func testDeleteIndexWithClient() async throws { let jsonString = """ {"taskUid":0,"indexUid":"books","status":"enqueued","type":"indexDeletion","enqueuedAt":"2022-07-21T22:05:00.976623757Z"} """ @@ -276,24 +170,11 @@ class IndexesTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Delete index with client instance") - - self.client.deleteIndex(self.uid) { result in - switch result { - case .success(let task): - XCTAssertEqual(0, task.taskUid) - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to delete index") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let task = try await self.client.deleteIndex(self.uid) + XCTAssertEqual(0, task.taskUid) } - func testDeleteIndex() { + func testDeleteIndex() async throws { let jsonString = """ {"taskUid":0,"indexUid":"books","status":"enqueued","type":"indexDeletion","enqueuedAt":"2022-07-21T22:05:00.976623757Z"} """ @@ -302,21 +183,7 @@ class IndexesTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Delete index") - - self.index.delete { result in - switch result { - case .success(let task): - XCTAssertEqual(0, task.taskUid) - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to delete index") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let task = try await self.index.delete() + XCTAssertEqual(0, task.taskUid) } } -// swiftlint:enable force_unwrapping diff --git a/Tests/MeiliSearchUnitTests/KeysTests.swift b/Tests/MeiliSearchUnitTests/KeysTests.swift index 9eeda04b..83df748f 100644 --- a/Tests/MeiliSearchUnitTests/KeysTests.swift +++ b/Tests/MeiliSearchUnitTests/KeysTests.swift @@ -13,7 +13,7 @@ class KeysTests: XCTestCase { index = client.index(self.uid) } - func testGetKeysWithParameters() { + func testGetKeysWithParameters() async throws { let jsonString = """ { "results": [], @@ -27,24 +27,8 @@ class KeysTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get keys with parameters") - - self.client.getKeys(params: KeysQuery(limit: 2, offset: 10)) { result in - switch result { - case .success: - let requestQuery = self.session.nextDataTask.request?.url?.query - - XCTAssertEqual(requestQuery, "limit=2&offset=10") - - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to get all Indexes") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + _ = try await self.client.getKeys(params: KeysQuery(limit: 2, offset: 10)) + let requestQuery = self.session.nextDataTask.request?.url?.query + XCTAssertEqual(requestQuery, "limit=2&offset=10") } } -// swiftlint:enable force_unwrapping diff --git a/Tests/MeiliSearchUnitTests/MockURLSession.swift b/Tests/MeiliSearchUnitTests/MockURLSession.swift index e187436a..eb46919a 100644 --- a/Tests/MeiliSearchUnitTests/MockURLSession.swift +++ b/Tests/MeiliSearchUnitTests/MockURLSession.swift @@ -4,7 +4,6 @@ import Foundation import FoundationNetworking #endif -// swiftlint:disable force_unwrapping class MockURLSession: URLSessionProtocol { private(set) var nextDataTask = MockURLSessionDataTask() @@ -83,4 +82,3 @@ struct ResponsePayload { static let `default` = ResponsePayload(nextType: ResponseStatus.success, nextData: nil, nextError: nil, nextCode: 200) } -// swiftlint:enable force_unwrapping diff --git a/Tests/MeiliSearchUnitTests/SearchTests.swift b/Tests/MeiliSearchUnitTests/SearchTests.swift index cd9ef8e3..fccd3924 100644 --- a/Tests/MeiliSearchUnitTests/SearchTests.swift +++ b/Tests/MeiliSearchUnitTests/SearchTests.swift @@ -1,8 +1,6 @@ @testable import MeiliSearch import XCTest -// swiftlint:disable force_unwrapping - private struct Movie: Codable, Equatable { let id: Int let title: String @@ -30,7 +28,7 @@ class SearchTests: XCTestCase { index = client.index("movies_test") } - func testSearchForBotmanMovie() throws { + func testSearchForBotmanMovie() async throws { let jsonString = """ { "hits": [ @@ -58,70 +56,16 @@ class SearchTests: XCTestCase { """ // Prepare the mock server - let data = jsonString.data(using: .utf8)! - let stubSearchResult: Searchable = try Constants.customJSONDecoder.decode(Searchable.self, from: data) + let stubSearchResult: Searchable = try decodeJSON(from: jsonString) session.pushData(jsonString) // Start the test with the mocked server let searchParameters = SearchParameters.query("botman") - let expectation = XCTestExpectation(description: "Searching for botman") - typealias MeiliResult = Result, Swift.Error> - - self.index.search(searchParameters) { (result: MeiliResult) in - switch result { - case .success(let searchResult): - XCTAssertEqual(stubSearchResult, searchResult) - expectation.fulfill() - case .failure: - XCTFail("Failed to search for botman") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) - } - - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) - func testSearchForBotmanMovieAsync() async throws { - let jsonString = """ - { - "hits": [ - { - "id": 29751, - "title": "Batman Unmasked: The Psychology of the Dark Knight", - "poster": "https://image.tmdb.org/t/p/w1280/jjHu128XLARc2k4cJrblAvZe0HE.jpg", - "overview": "Delve into the world of Batman and the vigilante justice tha", - "release_date": "2020-04-04T19:59:49.259572Z" - }, - { - "id": 471474, - "title": "Batman: Gotham by Gaslight", - "poster": "https://image.tmdb.org/t/p/w1280/7souLi5zqQCnpZVghaXv0Wowi0y.jpg", - "overview": "ve Victorian Age Gotham City, Batman begins his war on crime", - "release_date": "2020-04-04T19:59:49.259572Z" - } - ], - "offset": 0, - "limit": 20, - "processingTimeMs": 2, - "estimatedTotalHits": 2, - "query": "botman" - } - """ - - // Prepare the mock server - let data = jsonString.data(using: .utf8)! - let stubSearchResult: Searchable = try! Constants.customJSONDecoder.decode(Searchable.self, from: data) - session.pushData(jsonString) - - // Start the test with the mocked server - let searchParameters = SearchParameters.query("botman") - let searchResult: Searchable = try await self.index.search(searchParameters) XCTAssertEqual(stubSearchResult, searchResult) } - func testSearchForBotmanMovieFacets() throws { + func testSearchForBotmanMovieFacets() async throws { let jsonString = """ { "hits": [ @@ -149,8 +93,7 @@ class SearchTests: XCTestCase { """ // Prepare the mock server - let data = jsonString.data(using: .utf8)! - let stubSearchResult: Searchable = try Constants.customJSONDecoder.decode(Searchable.self, from: data) + let stubSearchResult: Searchable = try decodeJSON(from: jsonString) session.pushData(jsonString) // Start the test with the mocked server @@ -160,25 +103,11 @@ class SearchTests: XCTestCase { sort: ["id:asc"] ) - let expectation = XCTestExpectation(description: "Searching for botman") - typealias MeiliResult = Result, Swift.Error> - - self.index.search(searchParameters) { (result: MeiliResult) in - switch result { - case .success(let searchResult): - print(searchResult) - XCTAssertEqual(stubSearchResult, searchResult) - expectation.fulfill() - case .failure: - XCTFail("Failed to search for botman") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let searchResult: Searchable = try await self.index.search(searchParameters) + XCTAssertEqual(stubSearchResult, searchResult) } - func testShouldFilterValuesWithSpaces() { + func testShouldFilterValuesWithSpaces() async throws { let jsonString = """ { "hits": [ @@ -269,25 +198,11 @@ class SearchTests: XCTestCase { sort: ["id:asc"] ) - let expectation = XCTestExpectation(description: "Searching for the hobbit") - typealias MeiliResult = Result, Swift.Error> - - index.search(searchParameters) { (result: MeiliResult) in - switch result { - case .success(let searchResult): - XCTAssertEqual(stubSearchResult, searchResult) - expectation.fulfill() - case .failure(let err): - print(err) - XCTFail("Failed to search for hobbit") - expectation.fulfill() - } - } - - wait(for: [expectation], timeout: TESTS_TIME_OUT) + let searchResult: Searchable = try await index.search(searchParameters) + XCTAssertEqual(stubSearchResult, searchResult) } - func testSearchWithFinitePagination() throws { + func testSearchWithFinitePagination() async throws { let jsonString = """ { "hits": [ @@ -316,35 +231,19 @@ class SearchTests: XCTestCase { """ // Prepare the mock server - let data = jsonString.data(using: .utf8)! - let stubSearchResult: Searchable = try Constants.customJSONDecoder.decode(Searchable.self, from: data) + let stubSearchResult: Searchable = try decodeJSON(from: jsonString) session.pushData(jsonString) // Start the test with the mocked server let searchParameters = SearchParameters(query: "botman", hitsPerPage: 10) - let expectation = XCTestExpectation(description: "Searching for botman with finite pagination") - typealias MeiliResult = Result, Swift.Error> - - self.index.search(searchParameters) { (result: MeiliResult) in - switch result { - case .success(let searchResult): - let result = searchResult as! FiniteSearchResult - - XCTAssertEqual(stubSearchResult, searchResult) - XCTAssertEqual(result.totalPages, 1) - XCTAssertEqual(result.totalHits, 2) - XCTAssertEqual(result.page, 1) - XCTAssertEqual(result.query, "botman") - XCTAssertEqual(result.processingTimeMs, 2) - - expectation.fulfill() - case .failure: - XCTFail("Failed to search for botman with finite pagination") - expectation.fulfill() - } - } + let searchResult: Searchable = try await self.index.search(searchParameters) + let result = searchResult as! FiniteSearchResult - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + XCTAssertEqual(stubSearchResult, searchResult) + XCTAssertEqual(result.totalPages, 1) + XCTAssertEqual(result.totalHits, 2) + XCTAssertEqual(result.page, 1) + XCTAssertEqual(result.query, "botman") + XCTAssertEqual(result.processingTimeMs, 2) } } -// swiftlint:enable force_unwrapping diff --git a/Tests/MeiliSearchUnitTests/SettingsTests.swift b/Tests/MeiliSearchUnitTests/SettingsTests.swift index 9edd3d44..4bd353ad 100644 --- a/Tests/MeiliSearchUnitTests/SettingsTests.swift +++ b/Tests/MeiliSearchUnitTests/SettingsTests.swift @@ -1,7 +1,6 @@ @testable import MeiliSearch import XCTest -// swiftlint:disable force_cast class SettingsTests: XCTestCase { private var client: MeiliSearch! private var index: Indexes! @@ -60,27 +59,17 @@ class SettingsTests: XCTestCase { // MARK: Settings - func testGetSettings() throws { + func testGetSettings() async throws { // Prepare the mock server let stubSetting: SettingResult = try buildStubSettingResult(from: json) session.pushData(json) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get settings") - self.index.getSettings { result in - switch result { - case .success(let setting): - XCTAssertEqual(stubSetting, setting) - case .failure: - XCTFail("Failed to get settings") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let setting = try await self.index.getSettings() + XCTAssertEqual(stubSetting, setting) } - func testUpdateSettings() throws { + func testUpdateSettings() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -94,22 +83,11 @@ class SettingsTests: XCTestCase { let setting: Setting = try buildStubSetting(from: json) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update settings") - - self.index.updateSettings(setting) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update settings") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateSettings(setting) + XCTAssertEqual(stubTask, update) } - func testResetSettings() throws { + func testResetSettings() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -121,24 +99,13 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Reset settings") - - self.index.resetSettings { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to reset settings") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.resetSettings() + XCTAssertEqual(stubTask, update) } // MARK: Synonyms - func testGetSynonyms() throws { + func testGetSynonyms() async throws { let jsonString = """ { "wolverine": ["xmen", "logan"], @@ -155,22 +122,11 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get synonyms") - - self.index.getSynonyms { result in - switch result { - case .success(let synonyms): - XCTAssertEqual(stubSynonyms, synonyms) - case .failure: - XCTFail("Failed to get synonyms") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let synonyms = try await self.index.getSynonyms() + XCTAssertEqual(stubSynonyms, synonyms) } - func testUpdateSynonyms() throws { + func testUpdateSynonyms() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -194,21 +150,11 @@ class SettingsTests: XCTestCase { with: jsonData, options: []) as! [String: [String]] // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update synonyms") - self.index.updateSynonyms(synonyms) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update synonyms") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateSynonyms(synonyms) + XCTAssertEqual(stubTask, update) } - func testResetSynonyms() throws { + func testResetSynonyms() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -221,24 +167,13 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Reset synonyms") - - self.index.resetSynonyms { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to reset synonyms") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.resetSynonyms() + XCTAssertEqual(stubTask, update) } // MARK: Stop words - func testGetStopWords() throws { + func testGetStopWords() async throws { let jsonString = """ ["of", "the", "to"] """ @@ -250,22 +185,11 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get stop-words") - - self.index.getStopWords { result in - switch result { - case .success(let stopWords): - XCTAssertEqual(stubStopWords, stopWords) - case .failure: - XCTFail("Failed to get stop-words") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let stopWords = try await self.index.getStopWords() + XCTAssertEqual(stubStopWords, stopWords) } - func testUpdateStopWords() throws { + func testUpdateStopWords() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -284,21 +208,11 @@ class SettingsTests: XCTestCase { with: Data(json.utf8), options: []) as! [String] // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update stop-words") - self.index.updateStopWords(stopWords) { result in - switch result { - case .success(let update): - XCTAssertEqual(update, stubTask) - case .failure: - XCTFail("Failed to update stop-words") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateStopWords(stopWords) + XCTAssertEqual(update, stubTask) } - func testResetStopWords() throws { + func testResetStopWords() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -312,24 +226,13 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Reset stop-words") - - self.index.resetStopWords { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to reset stop-words") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.resetStopWords() + XCTAssertEqual(stubTask, update) } // MARK: Ranking rules - func testGetRankingRules() throws { + func testGetRankingRules() async throws { let jsonString = """ [ "words", @@ -349,22 +252,11 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get ranking rules") - - self.index.getRankingRules { result in - switch result { - case .success(let rankingRules): - XCTAssertEqual(stubRankingRules, rankingRules) - case .failure: - XCTFail("Failed to get ranking rules") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let rankingRules = try await self.index.getRankingRules() + XCTAssertEqual(stubRankingRules, rankingRules) } - func testUpdateRankingRules() throws { + func testUpdateRankingRules() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -382,22 +274,11 @@ class SettingsTests: XCTestCase { with: Data(json.utf8), options: []) as! [String] // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update ranking rules") - - self.index.updateRankingRules(stopWords) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update ranking rules") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateRankingRules(stopWords) + XCTAssertEqual(stubTask, update) } - func testResetRankingRules() throws { + func testResetRankingRules() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -411,24 +292,13 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Reset ranking rules") - - self.index.resetRankingRules { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to reset ranking rules") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.resetRankingRules() + XCTAssertEqual(stubTask, update) } // MARK: Distinct Attribute - func testGetDistinctAttribute() throws { + func testGetDistinctAttribute() async throws { let stubDistinctAttribute: String = """ "movie_id" """ @@ -437,22 +307,11 @@ class SettingsTests: XCTestCase { session.pushData(stubDistinctAttribute) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get distinct attribute") - - self.index.getDistinctAttribute { result in - switch result { - case .success(let distinctAttribute): - XCTAssertEqual("movie_id", distinctAttribute) - case .failure: - XCTFail("Failed to get distinct attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let distinctAttribute = try await self.index.getDistinctAttribute() + XCTAssertEqual("movie_id", distinctAttribute) } - func testUpdateDistinctAttribute() throws { + func testUpdateDistinctAttribute() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -466,22 +325,11 @@ class SettingsTests: XCTestCase { let distinctAttribute = "movie_id" // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update distinct attribute") - - self.index.updateDistinctAttribute(distinctAttribute) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update distinct attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateDistinctAttribute(distinctAttribute) + XCTAssertEqual(stubTask, update) } - func testResetDistinctAttribute() throws { + func testResetDistinctAttribute() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -494,24 +342,13 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Reset distinct attribute") - - self.index.resetDistinctAttribute { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to reset distinct attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.resetDistinctAttribute() + XCTAssertEqual(stubTask, update) } // MARK: Searchable Attribute - func testGetSearchableAttributes() throws { + func testGetSearchableAttributes() async throws { let jsonString = """ ["title", "description", "uid"] """ @@ -523,22 +360,11 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get searchable attribute") - - self.index.getSearchableAttributes { result in - switch result { - case .success(let searchableAttribute): - XCTAssertEqual(stubSearchableAttribute, searchableAttribute) - case .failure: - XCTFail("Failed to get searchable attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let searchableAttribute = try await self.index.getSearchableAttributes() + XCTAssertEqual(stubSearchableAttribute, searchableAttribute) } - func testUpdateSearchableAttributes() throws { + func testUpdateSearchableAttributes() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -558,21 +384,11 @@ class SettingsTests: XCTestCase { with: jsonData, options: []) as! [String] // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update searchable attribute") - self.index.updateSearchableAttributes(searchableAttribute) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update searchable attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateSearchableAttributes(searchableAttribute) + XCTAssertEqual(stubTask, update) } - func testResetSearchableAttributes() throws { + func testResetSearchableAttributes() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -585,23 +401,13 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Reset searchable attribute") - self.index.resetSearchableAttributes { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to reset searchable attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.resetSearchableAttributes() + XCTAssertEqual(stubTask, update) } // MARK: Displayed Attributes - func testGetDisplayedAttributes() throws { + func testGetDisplayedAttributes() async throws { let jsonString = """ ["title", "description", "release_date", "rank", "poster"] """ @@ -613,22 +419,11 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get displayed attribute") - - self.index.getDisplayedAttributes { result in - switch result { - case .success(let displayedAttributes): - XCTAssertEqual(stubDisplayedAttributes, displayedAttributes) - case .failure: - XCTFail("Failed to get displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let displayedAttributes = try await self.index.getDisplayedAttributes() + XCTAssertEqual(stubDisplayedAttributes, displayedAttributes) } - func testUpdateDisplayedAttributes() throws { + func testUpdateDisplayedAttributes() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -650,22 +445,11 @@ class SettingsTests: XCTestCase { with: jsonData, options: []) as! [String] // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update displayed attribute") - - self.index.updateDisplayedAttributes(displayedAttributes) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateDisplayedAttributes(displayedAttributes) + XCTAssertEqual(stubTask, update) } - func testResetDisplayedAttributes() throws { + func testResetDisplayedAttributes() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -678,24 +462,13 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Reset displayed attribute") - - self.index.resetDisplayedAttributes { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to reset displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.resetDisplayedAttributes() + XCTAssertEqual(stubTask, update) } // MARK: Filterable Attributes - func testGetFilterableAttributes() throws { + func testGetFilterableAttributes() async throws { let jsonString = """ ["genre", "director"] """ @@ -704,22 +477,11 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get displayed attribute") - - self.index.getFilterableAttributes { result in - switch result { - case .success(let filterableAttributes): - XCTAssertFalse(filterableAttributes.isEmpty) - case .failure: - XCTFail("Failed to get displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let filterableAttributes = try await self.index.getFilterableAttributes() + XCTAssertFalse(filterableAttributes.isEmpty) } - func testUpdateFilterableAttributes() throws { + func testUpdateFilterableAttributes() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -734,22 +496,11 @@ class SettingsTests: XCTestCase { let attributes: [String] = ["genre", "director"] // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update displayed attribute") - - self.index.updateFilterableAttributes(attributes) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateFilterableAttributes(attributes) + XCTAssertEqual(stubTask, update) } - func testResetFilterableAttributes() throws { + func testResetFilterableAttributes() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -763,24 +514,13 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update displayed attribute") - - self.index.resetFilterableAttributes { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.resetFilterableAttributes() + XCTAssertEqual(stubTask, update) } // MARK: Filterable Attributes - func testGetSortableAttributes() throws { + func testGetSortableAttributes() async throws { let jsonString = """ ["genre", "director"] """ @@ -789,22 +529,11 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get displayed attribute") - - self.index.getSortableAttributes { result in - switch result { - case .success(let sortableAttributes): - XCTAssertFalse(sortableAttributes.isEmpty) - case .failure: - XCTFail("Failed to get displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let sortableAttributes = try await self.index.getSortableAttributes() + XCTAssertFalse(sortableAttributes.isEmpty) } - func testUpdateSortableAttributes() throws { + func testUpdateSortableAttributes() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -819,22 +548,11 @@ class SettingsTests: XCTestCase { let attributes: [String] = ["genre", "director"] // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update displayed attribute") - - self.index.updateSortableAttributes(attributes) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateSortableAttributes(attributes) + XCTAssertEqual(stubTask, update) } - func testResetSortableAttributes() throws { + func testResetSortableAttributes() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -847,24 +565,13 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update displayed attribute") - - self.index.resetSortableAttributes { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.resetSortableAttributes() + XCTAssertEqual(stubTask, update) } // MARK: Typo Tolerance - func testGetTypoTolerance() { + func testGetTypoTolerance() async throws { let jsonString = """ {"enabled":true,"minWordSizeForTypos":{"oneTypo":3,"twoTypos":7},"disableOnWords":["of", "the"],"disableOnAttributes":["genre"]} """ @@ -873,26 +580,15 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get displayed attribute") - - self.index.getTypoTolerance { result in - switch result { - case .success(let typoTolerance): - XCTAssertTrue(typoTolerance.enabled) - XCTAssertEqual(typoTolerance.minWordSizeForTypos.oneTypo, 3) - XCTAssertEqual(typoTolerance.minWordSizeForTypos.twoTypos, 7) - XCTAssertFalse(typoTolerance.disableOnWords.isEmpty) - XCTAssertFalse(typoTolerance.disableOnAttributes.isEmpty) - case .failure: - XCTFail("Failed to get displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let typoTolerance = try await self.index.getTypoTolerance() + XCTAssertTrue(typoTolerance.enabled) + XCTAssertEqual(typoTolerance.minWordSizeForTypos.oneTypo, 3) + XCTAssertEqual(typoTolerance.minWordSizeForTypos.twoTypos, 7) + XCTAssertFalse(typoTolerance.disableOnWords.isEmpty) + XCTAssertFalse(typoTolerance.disableOnAttributes.isEmpty) } - func testUpdateTypoTolerance() throws { + func testUpdateTypoTolerance() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -905,22 +601,11 @@ class SettingsTests: XCTestCase { let typoTolerance: TypoTolerance = .init(enabled: false) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update displayed attribute") - - self.index.updateTypoTolerance(typoTolerance) { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.updateTypoTolerance(typoTolerance) + XCTAssertEqual(stubTask, update) } - func testResetTypoTolerance() throws { + func testResetTypoTolerance() async throws { let jsonString = """ {"taskUid":0,"indexUid":"movies_test","status":"enqueued","type":"settingsUpdate","enqueuedAt":"2022-07-27T19:03:50.494232841Z"} """ @@ -931,19 +616,8 @@ class SettingsTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Update displayed attribute") - - self.index.resetTypoTolerance { result in - switch result { - case .success(let update): - XCTAssertEqual(stubTask, update) - case .failure: - XCTFail("Failed to update displayed attribute") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let update = try await self.index.resetTypoTolerance() + XCTAssertEqual(stubTask, update) } private func buildStubSetting(from json: String) throws -> Setting { @@ -958,4 +632,3 @@ class SettingsTests: XCTestCase { return try decoder.decode(SettingResult.self, from: data) } } -// swiftlint:enable force_cast diff --git a/Tests/MeiliSearchUnitTests/StatsTests.swift b/Tests/MeiliSearchUnitTests/StatsTests.swift index 601284c5..299aeb25 100755 --- a/Tests/MeiliSearchUnitTests/StatsTests.swift +++ b/Tests/MeiliSearchUnitTests/StatsTests.swift @@ -1,8 +1,6 @@ @testable import MeiliSearch import XCTest -// swiftlint:disable force_unwrapping - class StatsTests: XCTestCase { private var client: MeiliSearch! private var index: Indexes! @@ -15,7 +13,7 @@ class StatsTests: XCTestCase { index = client.index(self.uid) } - func testStats() throws { + func testStats() async throws { let jsonString = """ { "numberOfDocuments": 19654, @@ -31,27 +29,16 @@ class StatsTests: XCTestCase { """ // Prepare the mock server - let jsonData = jsonString.data(using: .utf8)! - let stubStats: Stat = try Constants.customJSONDecoder.decode(Stat.self, from: jsonData) + let stubStats: Stat = try decodeJSON(from: jsonString) session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Check Movies stats") - self.index.stats { result in - switch result { - case .success(let stats): - XCTAssertEqual(stubStats, stats) - case .failure: - XCTFail("Failed to check Movies stats") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let stats = try await self.index.stats() + XCTAssertEqual(stubStats, stats) } - func testAllStats() throws { + func testAllStats() async throws { let jsonString = """ { "databaseSize": 447819776, @@ -81,25 +68,12 @@ class StatsTests: XCTestCase { } """ // Prepare the mock server - let jsonData = jsonString.data(using: .utf8)! - let stubAllStats: AllStats = try Constants.customJSONDecoder.decode(AllStats.self, from: jsonData) + let stubAllStats: AllStats = try decodeJSON(from: jsonString) session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Check all indexes stats") - - self.client.allStats { result in - switch result { - case .success(let allStats): - XCTAssertEqual(stubAllStats, allStats) - case .failure: - XCTFail("Failed to check all indexes stats") - } - expectation.fulfill() - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let allStats = try await self.client.allStats() + XCTAssertEqual(stubAllStats, allStats) } } -// swiftlint:enable force_unwrapping diff --git a/Tests/MeiliSearchUnitTests/SystemTests.swift b/Tests/MeiliSearchUnitTests/SystemTests.swift index 0fa08ac4..bf69cbaa 100755 --- a/Tests/MeiliSearchUnitTests/SystemTests.swift +++ b/Tests/MeiliSearchUnitTests/SystemTests.swift @@ -1,8 +1,6 @@ @testable import MeiliSearch import XCTest -// swiftlint:disable force_unwrapping - class SystemTests: XCTestCase { private var client: MeiliSearch! @@ -13,118 +11,61 @@ class SystemTests: XCTestCase { client = try MeiliSearch(host: "http://localhost:7700", apiKey: "masterKey", session: session) } - func testHealthStatusAvailable() throws { + func testHealthStatusAvailable() async throws { // Prepare the mock server - let jsonString = """ - { - "status": "available" - } - """ - - let jsonData = jsonString.data(using: .utf8)! - - let expectedHealthBody: Health = try Constants.customJSONDecoder.decode(Health.self, from: jsonData) + { + "status": "available" + } + """ + let expectedHealthBody: Health = try decodeJSON(from: jsonString) session.pushData(jsonString, code: 200) // Start the test with the mocked server - - let expectation = XCTestExpectation(description: "Check body of health server on health method") - - self.client.health { result in - switch result { - case .success(let body): - XCTAssertEqual(expectedHealthBody, body) - expectation.fulfill() - case .failure: - XCTFail("Failed on available status check on health method") - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let body = try await self.client.health() + XCTAssertEqual(expectedHealthBody, body) } - func testIsHealthyTrue() { + func testIsHealthyTrue() async throws { // Prepare the mock server - let jsonString = """ - { - "status": "available" - } - """ + { + "status": "available" + } + """ session.pushData(jsonString, code: 200) // Start the test with the mocked server - - let expectation = XCTestExpectation(description: "Check if is healthy is true") - - self.client.isHealthy { result in - if result == true { - XCTAssertEqual(result, true) - expectation.fulfill() - } else { - XCTFail("Failed on isHealthy should be true") - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let result = await self.client.isHealthy() + XCTAssertTrue(result) } - func testIsHealthyFalse() { + func testIsHealthyFalse() async throws { // Prepare the mock server - session.pushData("", code: 400) // Start the test with the mocked server - - let expectation = XCTestExpectation(description: "Check if is healthy is false") - - self.client.isHealthy { result in - if result == false { - XCTAssertEqual(result, false) - expectation.fulfill() - } else { - XCTFail("Failed on isHealthy should be false") - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let result = await self.client.isHealthy() + XCTAssertFalse(result) } - func testVersion() throws { + func testVersion() async throws { // Prepare the mock server - let jsonString = """ - { - "commitSha": "b46889b5f0f2f8b91438a08a358ba8f05fc09fc1", - "commitDate": "2019-11-15T09:51:54.278247+00:00", - "pkgVersion": "0.1.1" - } - """ - - let jsonData = jsonString.data(using: .utf8)! - - let stubVersion: Version = try Constants.customJSONDecoder.decode(Version.self, from: jsonData) + { + "commitSha": "b46889b5f0f2f8b91438a08a358ba8f05fc09fc1", + "commitDate": "2019-11-15T09:51:54.278247+00:00", + "pkgVersion": "0.1.1" + } + """ + let stubVersion: Version = try decodeJSON(from: jsonString) session.pushData(jsonString) // Start the test with the mocked server - - let expectation = XCTestExpectation(description: "Load server version") - - self.client.version { result in - switch result { - case .success(let version): - XCTAssertEqual(stubVersion, version) - expectation.fulfill() - case .failure: - XCTFail("Failed to load server version") - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let version = try await client.version() + XCTAssertEqual(stubVersion, version) } } -// swiftlint:enable force_unwrapping diff --git a/Tests/MeiliSearchUnitTests/TasksTests.swift b/Tests/MeiliSearchUnitTests/TasksTests.swift index a27a5f69..956b7168 100644 --- a/Tests/MeiliSearchUnitTests/TasksTests.swift +++ b/Tests/MeiliSearchUnitTests/TasksTests.swift @@ -13,7 +13,7 @@ class TasksTests: XCTestCase { index = client.index(self.uid) } - func testGetTasksWithParametersFromClient() { + func testGetTasksWithParametersFromClient() async throws { let jsonString = """ { "results": [], @@ -28,24 +28,10 @@ class TasksTests: XCTestCase { session.pushData(jsonString) // Start the test with the mocked server - let expectation = XCTestExpectation(description: "Get keys with parameters") + let params = TasksQuery(limit: 20, from: 5, next: 98, types: [.indexCreation]) + _ = try await self.client.getTasks(params: params) - self.client.getTasks(params: TasksQuery(limit: 20, from: 5, next: 98, types: [.indexCreation])) { result in - switch result { - case .success: - let requestQuery = self.session.nextDataTask.request?.url?.query - - XCTAssertEqual(requestQuery, "from=5&limit=20&next=98&types=indexCreation") - - expectation.fulfill() - case .failure(let error): - dump(error) - XCTFail("Failed to get all Indexes") - expectation.fulfill() - } - } - - self.wait(for: [expectation], timeout: TESTS_TIME_OUT) + let requestQuery = self.session.nextDataTask.request?.url?.query + XCTAssertEqual(requestQuery, "from=5&limit=20&next=98&types=indexCreation") } } -// swiftlint:enable force_unwrapping diff --git a/Tests/MeiliSearchUnitTests/Utils.swift b/Tests/MeiliSearchUnitTests/Utils.swift index 9608fb02..e0f1af94 100644 --- a/Tests/MeiliSearchUnitTests/Utils.swift +++ b/Tests/MeiliSearchUnitTests/Utils.swift @@ -6,3 +6,8 @@ import XCTest @testable import MeiliSearch public let TESTS_TIME_OUT = 10.0 + +func decodeJSON(from string: String) throws -> T { + let data = Data(string.utf8) + return try Constants.customJSONDecoder.decode(T.self, from: data) +}