From c883383b5e697cf73573c8793b188d5e09726835 Mon Sep 17 00:00:00 2001 From: algolia-bot Date: Wed, 4 Sep 2024 10:52:14 +0000 Subject: [PATCH] feat(clients): add helper to check if an index exists (#3646) (generated) [skip ci] Co-authored-by: Pierre Millot Co-authored-by: Thomas Raffray --- .../algolia/search/api_search.go | 17 ++++ .../java/com/algolia/api/SearchClient.java | 12 +++ .../client-search/src/searchClient.ts | 31 +++++-- .../lib/Api/SearchClient.php | 14 +++ .../algoliasearch/search/client.py | 13 +++ .../lib/algolia/api/search_client.rb | 12 +++ snippets/csharp/src/Search.cs | 48 ++++++++++ snippets/dart/lib/search.dart | 45 +++++++++ snippets/go/src/search.go | 84 +++++++++++++++++ snippets/guides/search-snippets.json | 50 ++++++++++ snippets/java/build.gradle | 5 + .../src/test/java/com/algolia/Search.java | 39 ++++++++ snippets/javascript/src/search.ts | 48 ++++++++++ .../kotlin/com/algolia/snippets/Search.kt | 51 +++++++++++ snippets/php/src/Search.php | 63 +++++++++++++ snippets/python/search.py | 69 ++++++++++++++ snippets/ruby/search.rb | 57 ++++++++++++ snippets/swift/Sources/Search.swift | 39 ++++++++ specs/bundled/search.yml | 27 ++++++ .../src/generated/client/Abtesting.test.cs | 2 + .../src/generated/client/Analytics.test.cs | 2 + .../src/generated/client/Ingestion.test.cs | 1 + .../src/generated/client/Insights.test.cs | 2 + .../src/generated/client/Monitoring.test.cs | 1 + .../src/generated/client/Recommend.test.cs | 2 + .../src/generated/client/Search.test.cs | 82 +++++++++++++++++ .../csharp/src/generated/client/Usage.test.cs | 2 + .../dart/test/client/insights_test.dart | 4 +- .../dart/test/client/recommend_test.dart | 4 +- .../output/dart/test/client/search_test.dart | 4 +- tests/output/go/tests/client/search_test.go | 81 ++++++++++++++++- tests/output/java/build.gradle | 5 + .../com/algolia/client/Abtesting.test.java | 4 - .../com/algolia/client/Analytics.test.java | 4 - .../com/algolia/client/Ingestion.test.java | 3 - .../com/algolia/client/Insights.test.java | 4 - .../com/algolia/client/Monitoring.test.java | 3 - .../algolia/client/Personalization.test.java | 2 - .../algolia/client/QuerySuggestions.test.java | 2 - .../com/algolia/client/Recommend.test.java | 4 - .../java/com/algolia/client/Search.test.java | 52 ++++++++++- .../java/com/algolia/client/Usage.test.java | 4 - .../javascript/src/client/search.test.ts | 37 +++++++- .../com/algolia/benchmark/SearchTest.kt | 2 + .../kotlin/com/algolia/client/SearchTest.kt | 48 +++++++++- tests/output/php/src/client/SearchTest.php | 48 +++++++++- .../output/python/tests/client/search_test.py | 52 ++++++++++- tests/output/ruby/test/client/search_test.rb | 69 +++++++++++++- .../swift/Tests/client/SearchTests.swift | 91 +++++++++++-------- 49 files changed, 1253 insertions(+), 92 deletions(-) diff --git a/clients/algoliasearch-client-go/algolia/search/api_search.go b/clients/algoliasearch-client-go/algolia/search/api_search.go index 4e5b7012a7..8b5682ff5b 100644 --- a/clients/algoliasearch-client-go/algolia/search/api_search.go +++ b/clients/algoliasearch-client-go/algolia/search/api_search.go @@ -9965,3 +9965,20 @@ func (c *APIClient) ReplaceAllObjects(indexName string, objects []map[string]any MoveOperationResponse: *moveResp, }, nil } + +// Exists returns whether an initialized index exists or not, along with a nil +// error. When encountering a network error, a non-nil error is returned along +// with false. +func (c *APIClient) IndexExists(indexName string) (bool, error) { + _, err := c.GetSettings(c.NewApiGetSettingsRequest(indexName)) + if err == nil { + return true, nil + } + + var apiErr *APIError + if errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound { + return false, nil + } + + return false, err +} diff --git a/clients/algoliasearch-client-java/algoliasearch/src/main/java/com/algolia/api/SearchClient.java b/clients/algoliasearch-client-java/algoliasearch/src/main/java/com/algolia/api/SearchClient.java index ce4ff6f9ca..f09e75daa4 100644 --- a/clients/algoliasearch-client-java/algoliasearch/src/main/java/com/algolia/api/SearchClient.java +++ b/clients/algoliasearch-client-java/algoliasearch/src/main/java/com/algolia/api/SearchClient.java @@ -6743,4 +6743,16 @@ public Duration getSecuredApiKeyRemainingValidity(@Nonnull String securedApiKey) return Duration.ofSeconds(timeStamp - Instant.now().getEpochSecond()); } + + public boolean indexExists(String indexName) { + try { + getSettings(indexName); + } catch (AlgoliaApiException e) { + if (e.getStatusCode() == 404) { + return false; + } + throw e; + } + return true; + } } diff --git a/clients/algoliasearch-client-javascript/packages/client-search/src/searchClient.ts b/clients/algoliasearch-client-javascript/packages/client-search/src/searchClient.ts index 9b5f42c9ff..5797e6b47f 100644 --- a/clients/algoliasearch-client-javascript/packages/client-search/src/searchClient.ts +++ b/clients/algoliasearch-client-javascript/packages/client-search/src/searchClient.ts @@ -1,6 +1,13 @@ // Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. -import { createAuth, createTransporter, getAlgoliaAgent, shuffle, createIterablePromise } from '@algolia/client-common'; +import { + createAuth, + createTransporter, + getAlgoliaAgent, + shuffle, + ApiError, + createIterablePromise, +} from '@algolia/client-common'; import type { CreateClientOptions, Headers, @@ -8,7 +15,6 @@ import type { QueryParameters, Request, RequestOptions, - ApiError, IterableOptions, } from '@algolia/client-common'; @@ -643,6 +649,19 @@ export function createSearchClient({ return { copyOperationResponse, batchResponses, moveOperationResponse }; }, + async indexExists({ indexName }: GetSettingsProps): Promise { + try { + await this.getSettings({ indexName }); + } catch (error) { + if (error instanceof ApiError && error.status === 404) { + return false; + } + throw error; + } + + return true; + }, + /** * Helper: calls the `search` method but with certainty that we will only request Algolia records (hits) and not facets. * Disclaimer: We don't assert that the parameters you pass to this method only contains `hits` requests to prevent impacting search performances, this helper is purely for typing purposes. @@ -1045,7 +1064,6 @@ export function createSearchClient({ const requestPath = '/1/indexes/{indexName}/rules/clear'.replace('{indexName}', encodeURIComponent(indexName)); const headers: Headers = {}; const queryParameters: QueryParameters = {}; - if (forwardToReplicas !== undefined) { queryParameters.forwardToReplicas = forwardToReplicas.toString(); } @@ -1082,7 +1100,6 @@ export function createSearchClient({ const requestPath = '/1/indexes/{indexName}/synonyms/clear'.replace('{indexName}', encodeURIComponent(indexName)); const headers: Headers = {}; const queryParameters: QueryParameters = {}; - if (forwardToReplicas !== undefined) { queryParameters.forwardToReplicas = forwardToReplicas.toString(); } @@ -1454,6 +1471,7 @@ export function createSearchClient({ .replace('{objectID}', encodeURIComponent(objectID)); const headers: Headers = {}; const queryParameters: QueryParameters = {}; + if (forwardToReplicas !== undefined) { queryParameters.forwardToReplicas = forwardToReplicas.toString(); } @@ -1595,7 +1613,6 @@ export function createSearchClient({ if (length !== undefined) { queryParameters.length = length.toString(); } - if (indexName !== undefined) { queryParameters.indexName = indexName.toString(); } @@ -1642,6 +1659,7 @@ export function createSearchClient({ .replace('{objectID}', encodeURIComponent(objectID)); const headers: Headers = {}; const queryParameters: QueryParameters = {}; + if (attributesToRetrieve !== undefined) { queryParameters.attributesToRetrieve = attributesToRetrieve.toString(); } @@ -2381,10 +2399,10 @@ export function createSearchClient({ const requestPath = '/1/indexes/{indexName}/rules/batch'.replace('{indexName}', encodeURIComponent(indexName)); const headers: Headers = {}; const queryParameters: QueryParameters = {}; + if (forwardToReplicas !== undefined) { queryParameters.forwardToReplicas = forwardToReplicas.toString(); } - if (clearExistingRules !== undefined) { queryParameters.clearExistingRules = clearExistingRules.toString(); } @@ -2487,7 +2505,6 @@ export function createSearchClient({ if (forwardToReplicas !== undefined) { queryParameters.forwardToReplicas = forwardToReplicas.toString(); } - if (replaceExistingSynonyms !== undefined) { queryParameters.replaceExistingSynonyms = replaceExistingSynonyms.toString(); } diff --git a/clients/algoliasearch-client-php/lib/Api/SearchClient.php b/clients/algoliasearch-client-php/lib/Api/SearchClient.php index 2486b441ce..c851b6db82 100644 --- a/clients/algoliasearch-client-php/lib/Api/SearchClient.php +++ b/clients/algoliasearch-client-php/lib/Api/SearchClient.php @@ -7,6 +7,7 @@ use Algolia\AlgoliaSearch\Algolia; use Algolia\AlgoliaSearch\Configuration\SearchConfig; use Algolia\AlgoliaSearch\Exceptions\ExceededRetriesException; +use Algolia\AlgoliaSearch\Exceptions\NotFoundException; use Algolia\AlgoliaSearch\Exceptions\ValidUntilNotFoundException; use Algolia\AlgoliaSearch\Iterators\ObjectIterator; use Algolia\AlgoliaSearch\Iterators\RuleIterator; @@ -3098,6 +3099,19 @@ public static function getSecuredApiKeyRemainingValidity($securedApiKey) return $validUntil - time(); } + public function indexExists($indexName) + { + try { + $this->getSettings($indexName); + } catch (NotFoundException $e) { + return false; + } catch (Exception $e) { + throw $e; + } + + return true; + } + private function sendRequest($method, $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions, $useReadTransporter = false) { if (!isset($requestOptions['headers'])) { diff --git a/clients/algoliasearch-client-python/algoliasearch/search/client.py b/clients/algoliasearch-client-python/algoliasearch/search/client.py index b7b89d3c83..17d3ab14cf 100644 --- a/clients/algoliasearch-client-python/algoliasearch/search/client.py +++ b/clients/algoliasearch-client-python/algoliasearch/search/client.py @@ -596,6 +596,19 @@ async def _copy() -> UpdatedAtResponse: move_operation_response=move_operation_response, ) + async def index_exists(self, index_name: str) -> bool: + """ + Helper: Checks if the given `index_name` exists. + """ + try: + await self.get_settings(index_name) + except Exception as e: + if isinstance(e, RequestException) and e.status_code == 404: + return False + raise e + + return True + async def add_api_key_with_http_info( self, api_key: ApiKey, diff --git a/clients/algoliasearch-client-ruby/lib/algolia/api/search_client.rb b/clients/algoliasearch-client-ruby/lib/algolia/api/search_client.rb index b7d1121bab..a718a3903f 100644 --- a/clients/algoliasearch-client-ruby/lib/algolia/api/search_client.rb +++ b/clients/algoliasearch-client-ruby/lib/algolia/api/search_client.rb @@ -3532,5 +3532,17 @@ def replace_all_objects(index_name, objects, batch_size = 1000, request_options move_operation_response: move_operation_response ) end + + def index_exists?(index_name) + begin + get_settings(index_name) + rescue AlgoliaHttpError => e + return false if e.code == 404 + + raise e + end + + true + end end end diff --git a/snippets/csharp/src/Search.cs b/snippets/csharp/src/Search.cs index 01e3ceae19..6170c2c7f8 100644 --- a/snippets/csharp/src/Search.cs +++ b/snippets/csharp/src/Search.cs @@ -1000,6 +1000,54 @@ public async Task SnippetForSearchClientHasPendingMappings() // SEPARATOR< } + /// + /// Snippet for the IndexExists method. + /// + /// indexExists + /// + public async Task SnippetForSearchClientIndexExists() + { + // >SEPARATOR indexExists indexExists + // Initialize the client + var client = new SearchClient(new SearchConfig("YOUR_APP_ID", "YOUR_API_KEY")); + + // Call the API + var response = await client.IndexExistsAsync(""); + // SEPARATOR< + } + + /// + /// Snippet for the IndexExists method. + /// + /// indexNotExists + /// + public async Task SnippetForSearchClientIndexExists1() + { + // >SEPARATOR indexExists indexNotExists + // Initialize the client + var client = new SearchClient(new SearchConfig("YOUR_APP_ID", "YOUR_API_KEY")); + + // Call the API + var response = await client.IndexExistsAsync(""); + // SEPARATOR< + } + + /// + /// Snippet for the IndexExists method. + /// + /// indexExistsWithError + /// + public async Task SnippetForSearchClientIndexExists2() + { + // >SEPARATOR indexExists indexExistsWithError + // Initialize the client + var client = new SearchClient(new SearchConfig("YOUR_APP_ID", "YOUR_API_KEY")); + + // Call the API + var response = await client.IndexExistsAsync(""); + // SEPARATOR< + } + /// /// Snippet for the ListApiKeys method. /// diff --git a/snippets/dart/lib/search.dart b/snippets/dart/lib/search.dart index 655b071a0a..116ae306ce 100644 --- a/snippets/dart/lib/search.dart +++ b/snippets/dart/lib/search.dart @@ -916,6 +916,51 @@ void snippetForhasPendingMappings() async { // SEPARATOR< } +// Snippet for the indexExists method. +// +// indexExists +void snippetForindexExists() async { + // >SEPARATOR indexExists indexExists + // Initialize the client + final client = SearchClient(appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY'); + + // Call the API + final response = await client.indexExists( + indexName: "", + ); + // SEPARATOR< +} + +// Snippet for the indexExists method. +// +// indexNotExists +void snippetForindexExists1() async { + // >SEPARATOR indexExists indexNotExists + // Initialize the client + final client = SearchClient(appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY'); + + // Call the API + final response = await client.indexExists( + indexName: "", + ); + // SEPARATOR< +} + +// Snippet for the indexExists method. +// +// indexExistsWithError +void snippetForindexExists2() async { + // >SEPARATOR indexExists indexExistsWithError + // Initialize the client + final client = SearchClient(appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY'); + + // Call the API + final response = await client.indexExists( + indexName: "", + ); + // SEPARATOR< +} + // Snippet for the listApiKeys method. // // listApiKeys diff --git a/snippets/go/src/search.go b/snippets/go/src/search.go index 375888ce74..cb65c8c476 100644 --- a/snippets/go/src/search.go +++ b/snippets/go/src/search.go @@ -1381,6 +1381,90 @@ func SnippetForHasPendingMappingsOfSearch() { print(response) // SEPARATOR< } +func SnippetForIndexExistsOfSearch() { + /* + Snippet for the indexExists method. + + indexExists + */ + + // >SEPARATOR indexExists indexExists + // Initialize the client + client, err := search.NewClient("YOUR_APP_ID", "YOUR_API_KEY") + if err != nil { + // The client can fail to initialize if you pass an invalid parameter. + panic(err) + } + + // Call the API + response, err := client.IndexExists( + "", + ) + if err != nil { + // handle the eventual error + panic(err) + } + + // use the model directly + print(response) + // SEPARATOR< +} +func SnippetForIndexExistsOfSearch1() { + /* + Snippet for the indexExists method. + + indexNotExists + */ + + // >SEPARATOR indexExists indexNotExists + // Initialize the client + client, err := search.NewClient("YOUR_APP_ID", "YOUR_API_KEY") + if err != nil { + // The client can fail to initialize if you pass an invalid parameter. + panic(err) + } + + // Call the API + response, err := client.IndexExists( + "", + ) + if err != nil { + // handle the eventual error + panic(err) + } + + // use the model directly + print(response) + // SEPARATOR< +} +func SnippetForIndexExistsOfSearch2() { + /* + Snippet for the indexExists method. + + indexExistsWithError + */ + + // >SEPARATOR indexExists indexExistsWithError + // Initialize the client + client, err := search.NewClient("YOUR_APP_ID", "YOUR_API_KEY") + if err != nil { + // The client can fail to initialize if you pass an invalid parameter. + panic(err) + } + + // Call the API + response, err := client.IndexExists( + "", + ) + if err != nil { + // handle the eventual error + panic(err) + } + + // use the model directly + print(response) + // SEPARATOR< +} func SnippetForListApiKeysOfSearch() { /* Snippet for the listApiKeys method. diff --git a/snippets/guides/search-snippets.json b/snippets/guides/search-snippets.json index fdd3eb5b19..57bfe93ccb 100644 --- a/snippets/guides/search-snippets.json +++ b/snippets/guides/search-snippets.json @@ -129,6 +129,11 @@ "hasPendingMappings": { "default": "var response = await client.HasPendingMappingsAsync();" }, + "indexExists": { + "indexExists": "var response = await client.IndexExistsAsync(\"\");", + "indexNotExists": "var response = await client.IndexExistsAsync(\"\");", + "indexExistsWithError": "var response = await client.IndexExistsAsync(\"\");" + }, "listApiKeys": { "default": "var response = await client.ListApiKeysAsync();" }, @@ -367,6 +372,11 @@ "hasPendingMappings": { "default": "final response = await client.hasPendingMappings();" }, + "indexExists": { + "indexExists": "final response = await client.indexExists(\n indexName: \"\",\n);", + "indexNotExists": "final response = await client.indexExists(\n indexName: \"\",\n);", + "indexExistsWithError": "final response = await client.indexExists(\n indexName: \"\",\n);" + }, "listApiKeys": { "default": "final response = await client.listApiKeys();" }, @@ -605,6 +615,11 @@ "hasPendingMappings": { "default": "response, err := client.HasPendingMappings(client.NewApiHasPendingMappingsRequest())\nif err != nil {\n // handle the eventual error\n panic(err)\n}\n\n// use the model directly\nprint(response)" }, + "indexExists": { + "indexExists": "response, err := client.IndexExists(\n \"\",\n)\nif err != nil {\n // handle the eventual error\n panic(err)\n}\n\n// use the model directly\nprint(response)", + "indexNotExists": "response, err := client.IndexExists(\n \"\",\n)\nif err != nil {\n // handle the eventual error\n panic(err)\n}\n\n// use the model directly\nprint(response)", + "indexExistsWithError": "response, err := client.IndexExists(\n \"\",\n)\nif err != nil {\n // handle the eventual error\n panic(err)\n}\n\n// use the model directly\nprint(response)" + }, "listApiKeys": { "default": "response, err := client.ListApiKeys()\nif err != nil {\n // handle the eventual error\n panic(err)\n}\n\n// use the model directly\nprint(response)" }, @@ -843,6 +858,11 @@ "hasPendingMappings": { "default": "client.hasPendingMappings();" }, + "indexExists": { + "indexExists": "client.indexExists(\"\");", + "indexNotExists": "client.indexExists(\"\");", + "indexExistsWithError": "client.indexExists(\"\");" + }, "listApiKeys": { "default": "client.listApiKeys();" }, @@ -1081,6 +1101,11 @@ "hasPendingMappings": { "default": "const response = await client.hasPendingMappings();\n\n// use typed response\nconsole.log(response);" }, + "indexExists": { + "indexExists": "const response = await client.indexExists({ indexName: 'indexExistsYES' });\n\n// use typed response\nconsole.log(response);", + "indexNotExists": "const response = await client.indexExists({ indexName: 'indexExistsNO' });\n\n// use typed response\nconsole.log(response);", + "indexExistsWithError": "const response = await client.indexExists({ indexName: 'indexExistsERROR' });\n\n// use typed response\nconsole.log(response);" + }, "listApiKeys": { "default": "const response = await client.listApiKeys();\n\n// use typed response\nconsole.log(response);" }, @@ -1319,6 +1344,11 @@ "hasPendingMappings": { "default": "var response = client.hasPendingMappings()\n\n// Use the response\nprintln(response)" }, + "indexExists": { + "indexExists": "var response = client.indexExists(\n indexName = \"\",\n)\n\n// Use the response\nprintln(response)", + "indexNotExists": "var response = client.indexExists(\n indexName = \"\",\n)\n\n// Use the response\nprintln(response)", + "indexExistsWithError": "var response = client.indexExists(\n indexName = \"\",\n)\n\n// Use the response\nprintln(response)" + }, "listApiKeys": { "default": "var response = client.listApiKeys()\n\n// Use the response\nprintln(response)" }, @@ -1557,6 +1587,11 @@ "hasPendingMappings": { "default": "$response = $client->hasPendingMappings();\n\n// play with the response\nvar_dump($response);" }, + "indexExists": { + "indexExists": "$response = $client->indexExists(\n '',\n);\n\n// play with the response\nvar_dump($response);", + "indexNotExists": "$response = $client->indexExists(\n '',\n);\n\n// play with the response\nvar_dump($response);", + "indexExistsWithError": "$response = $client->indexExists(\n '',\n);\n\n// play with the response\nvar_dump($response);" + }, "listApiKeys": { "default": "$response = $client->listApiKeys();\n\n// play with the response\nvar_dump($response);" }, @@ -1795,6 +1830,11 @@ "hasPendingMappings": { "default": "response = await _client.has_pending_mappings()\n\n# use the class directly\nprint(response)\n\n# print the JSON response\nprint(response.to_json())" }, + "indexExists": { + "indexExists": "response = await _client.index_exists(\n index_name=\"\",\n)\n\n# use the class directly\nprint(response)\n\n# print the JSON response\nprint(response.to_json())", + "indexNotExists": "response = await _client.index_exists(\n index_name=\"\",\n)\n\n# use the class directly\nprint(response)\n\n# print the JSON response\nprint(response.to_json())", + "indexExistsWithError": "response = await _client.index_exists(\n index_name=\"\",\n)\n\n# use the class directly\nprint(response)\n\n# print the JSON response\nprint(response.to_json())" + }, "listApiKeys": { "default": "response = await _client.list_api_keys()\n\n# use the class directly\nprint(response)\n\n# print the JSON response\nprint(response.to_json())" }, @@ -2033,6 +2073,11 @@ "hasPendingMappings": { "default": "response = client.has_pending_mappings\n\n# use the class directly\nputs(response)\n\n# print the JSON response\nputs(response.to_json)" }, + "indexExists": { + "indexExists": "response = client.index_exists(\"\")\n\n# use the class directly\nputs(response)\n\n# print the JSON response\nputs(response.to_json)", + "indexNotExists": "response = client.index_exists(\"\")\n\n# use the class directly\nputs(response)\n\n# print the JSON response\nputs(response.to_json)", + "indexExistsWithError": "response = client.index_exists(\"\")\n\n# use the class directly\nputs(response)\n\n# print the JSON response\nputs(response.to_json)" + }, "listApiKeys": { "default": "response = client.list_api_keys\n\n# use the class directly\nputs(response)\n\n# print the JSON response\nputs(response.to_json)" }, @@ -2480,6 +2525,11 @@ "hasPendingMappings": { "default": "let response = try await client.hasPendingMappings()" }, + "indexExists": { + "indexExists": "let response = try await client.indexExists(indexName: \"\")", + "indexNotExists": "let response = try await client.indexExists(indexName: \"\")", + "indexExistsWithError": "let response = try await client.indexExists(indexName: \"\")" + }, "listApiKeys": { "default": "let response = try await client.listApiKeys()" }, diff --git a/snippets/java/build.gradle b/snippets/java/build.gradle index ec9e5200fd..2594ac41f1 100644 --- a/snippets/java/build.gradle +++ b/snippets/java/build.gradle @@ -15,7 +15,12 @@ dependencies { testImplementation 'io.github.cdimascio:dotenv-java:3.0.1' } +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} + test() { + systemProperty "file.encoding", "UTF-8" useJUnitPlatform() testLogging { events "passed", "skipped", "failed" diff --git a/snippets/java/src/test/java/com/algolia/Search.java b/snippets/java/src/test/java/com/algolia/Search.java index 462dd54425..14acc08723 100644 --- a/snippets/java/src/test/java/com/algolia/Search.java +++ b/snippets/java/src/test/java/com/algolia/Search.java @@ -739,6 +739,45 @@ void snippetForHasPendingMappings() { // SEPARATOR< } + // Snippet for the indexExists method. + // + // indexExists + void snippetForIndexExists() { + // >SEPARATOR indexExists indexExists + // Initialize the client + SearchClient client = new SearchClient("YOUR_APP_ID", "YOUR_API_KEY"); + + // Call the API + client.indexExists(""); + // SEPARATOR< + } + + // Snippet for the indexExists method. + // + // indexNotExists + void snippetForIndexExists1() { + // >SEPARATOR indexExists indexNotExists + // Initialize the client + SearchClient client = new SearchClient("YOUR_APP_ID", "YOUR_API_KEY"); + + // Call the API + client.indexExists(""); + // SEPARATOR< + } + + // Snippet for the indexExists method. + // + // indexExistsWithError + void snippetForIndexExists2() { + // >SEPARATOR indexExists indexExistsWithError + // Initialize the client + SearchClient client = new SearchClient("YOUR_APP_ID", "YOUR_API_KEY"); + + // Call the API + client.indexExists(""); + // SEPARATOR< + } + // Snippet for the listApiKeys method. // // listApiKeys diff --git a/snippets/javascript/src/search.ts b/snippets/javascript/src/search.ts index 1b0181fede..b0f50d73dd 100644 --- a/snippets/javascript/src/search.ts +++ b/snippets/javascript/src/search.ts @@ -870,6 +870,54 @@ export async function snippetForHasPendingMappings(): Promise { // SEPARATOR< } +// Snippet for the indexExists method. +// +// indexExists +export async function snippetForIndexExists(): Promise { + // >SEPARATOR indexExists indexExists + // Initialize the client + const client = searchClient('YOUR_APP_ID', 'YOUR_API_KEY'); + + // Call the API + const response = await client.indexExists({ indexName: 'indexExistsYES' }); + + // use typed response + console.log(response); + // SEPARATOR< +} + +// Snippet for the indexExists method. +// +// indexNotExists +export async function snippetForIndexExists1(): Promise { + // >SEPARATOR indexExists indexNotExists + // Initialize the client + const client = searchClient('YOUR_APP_ID', 'YOUR_API_KEY'); + + // Call the API + const response = await client.indexExists({ indexName: 'indexExistsNO' }); + + // use typed response + console.log(response); + // SEPARATOR< +} + +// Snippet for the indexExists method. +// +// indexExistsWithError +export async function snippetForIndexExists2(): Promise { + // >SEPARATOR indexExists indexExistsWithError + // Initialize the client + const client = searchClient('YOUR_APP_ID', 'YOUR_API_KEY'); + + // Call the API + const response = await client.indexExists({ indexName: 'indexExistsERROR' }); + + // use typed response + console.log(response); + // SEPARATOR< +} + // Snippet for the listApiKeys method. // // listApiKeys diff --git a/snippets/kotlin/src/main/kotlin/com/algolia/snippets/Search.kt b/snippets/kotlin/src/main/kotlin/com/algolia/snippets/Search.kt index 0a17d7ae0f..87b7c3fdeb 100644 --- a/snippets/kotlin/src/main/kotlin/com/algolia/snippets/Search.kt +++ b/snippets/kotlin/src/main/kotlin/com/algolia/snippets/Search.kt @@ -1025,6 +1025,57 @@ class SnippetSearchClient { exitProcess(0) } + suspend fun snippetForIndexExists() { + // >SEPARATOR indexExists indexExists + // Initialize the client + val client = SearchClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") + + // Call the API + var response = client.indexExists( + indexName = "", + ) + + // Use the response + println(response) + // SEPARATOR< + + exitProcess(0) + } + + suspend fun snippetForIndexExists1() { + // >SEPARATOR indexExists indexNotExists + // Initialize the client + val client = SearchClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") + + // Call the API + var response = client.indexExists( + indexName = "", + ) + + // Use the response + println(response) + // SEPARATOR< + + exitProcess(0) + } + + suspend fun snippetForIndexExists2() { + // >SEPARATOR indexExists indexExistsWithError + // Initialize the client + val client = SearchClient(appId = "YOUR_APP_ID", apiKey = "YOUR_API_KEY") + + // Call the API + var response = client.indexExists( + indexName = "", + ) + + // Use the response + println(response) + // SEPARATOR< + + exitProcess(0) + } + suspend fun snippetForListApiKeys() { // >SEPARATOR listApiKeys default // Initialize the client diff --git a/snippets/php/src/Search.php b/snippets/php/src/Search.php index 31d29277b0..74b782a00d 100644 --- a/snippets/php/src/Search.php +++ b/snippets/php/src/Search.php @@ -1179,6 +1179,69 @@ public function snippetForHasPendingMappings() // SEPARATOR< } + /** + * Snippet for the IndexExists method. + * + * indexExists + */ + public function snippetForIndexExists() + { + // >SEPARATOR indexExists indexExists + // Initialize the client + $client = SearchClient::create('', ''); + + // Call the API + $response = $client->indexExists( + '', + ); + + // play with the response + var_dump($response); + // SEPARATOR< + } + + /** + * Snippet for the IndexExists method. + * + * indexNotExists + */ + public function snippetForIndexExists1() + { + // >SEPARATOR indexExists indexNotExists + // Initialize the client + $client = SearchClient::create('', ''); + + // Call the API + $response = $client->indexExists( + '', + ); + + // play with the response + var_dump($response); + // SEPARATOR< + } + + /** + * Snippet for the IndexExists method. + * + * indexExistsWithError + */ + public function snippetForIndexExists2() + { + // >SEPARATOR indexExists indexExistsWithError + // Initialize the client + $client = SearchClient::create('', ''); + + // Call the API + $response = $client->indexExists( + '', + ); + + // play with the response + var_dump($response); + // SEPARATOR< + } + /** * Snippet for the ListApiKeys method. * diff --git a/snippets/python/search.py b/snippets/python/search.py index 0a6b865c72..912bf38720 100644 --- a/snippets/python/search.py +++ b/snippets/python/search.py @@ -1301,6 +1301,75 @@ async def snippet_for_has_pending_mappings(): # SEPARATOR< +async def snippet_for_index_exists(): + """ + Snippet for the indexExists method. + + indexExists + """ + # >SEPARATOR indexExists indexExists + # Initialize the client + _client = SearchClient("YOUR_APP_ID", "YOUR_API_KEY") + + # Call the API + response = await _client.index_exists( + index_name="", + ) + + # use the class directly + print(response) + + # print the JSON response + print(response.to_json()) + # SEPARATOR< + + +async def snippet_for_index_exists1(): + """ + Snippet for the indexExists method. + + indexNotExists + """ + # >SEPARATOR indexExists indexNotExists + # Initialize the client + _client = SearchClient("YOUR_APP_ID", "YOUR_API_KEY") + + # Call the API + response = await _client.index_exists( + index_name="", + ) + + # use the class directly + print(response) + + # print the JSON response + print(response.to_json()) + # SEPARATOR< + + +async def snippet_for_index_exists2(): + """ + Snippet for the indexExists method. + + indexExistsWithError + """ + # >SEPARATOR indexExists indexExistsWithError + # Initialize the client + _client = SearchClient("YOUR_APP_ID", "YOUR_API_KEY") + + # Call the API + response = await _client.index_exists( + index_name="", + ) + + # use the class directly + print(response) + + # print the JSON response + print(response.to_json()) + # SEPARATOR< + + async def snippet_for_list_api_keys(): """ Snippet for the listApiKeys method. diff --git a/snippets/ruby/search.rb b/snippets/ruby/search.rb index 53899b9e1d..e5389e4a88 100644 --- a/snippets/ruby/search.rb +++ b/snippets/ruby/search.rb @@ -1017,6 +1017,63 @@ def snippet_for_has_pending_mappings # SEPARATOR< end +# Snippet for the indexExists method. +# +# indexExists +def snippet_for_index_exists + # >SEPARATOR indexExists indexExists + # Initialize the client + client = Algolia::SearchClient.create("YOUR_APP_ID", "YOUR_API_KEY") + + # Call the API + response = client.index_exists("") + + # use the class directly + puts(response) + + # print the JSON response + puts(response.to_json) + # SEPARATOR< +end + +# Snippet for the indexExists method. +# +# indexNotExists +def snippet_for_index_exists1 + # >SEPARATOR indexExists indexNotExists + # Initialize the client + client = Algolia::SearchClient.create("YOUR_APP_ID", "YOUR_API_KEY") + + # Call the API + response = client.index_exists("") + + # use the class directly + puts(response) + + # print the JSON response + puts(response.to_json) + # SEPARATOR< +end + +# Snippet for the indexExists method. +# +# indexExistsWithError +def snippet_for_index_exists2 + # >SEPARATOR indexExists indexExistsWithError + # Initialize the client + client = Algolia::SearchClient.create("YOUR_APP_ID", "YOUR_API_KEY") + + # Call the API + response = client.index_exists("") + + # use the class directly + puts(response) + + # print the JSON response + puts(response.to_json) + # SEPARATOR< +end + # Snippet for the listApiKeys method. # # listApiKeys diff --git a/snippets/swift/Sources/Search.swift b/snippets/swift/Sources/Search.swift index c869d09abe..fe0dc45ca7 100644 --- a/snippets/swift/Sources/Search.swift +++ b/snippets/swift/Sources/Search.swift @@ -759,6 +759,45 @@ final class SearchClientSnippet { // SEPARATOR< } + /// Snippet for the indexExists method. + /// + /// indexExists + func snippetForIndexExists() async throws { + // >SEPARATOR indexExists indexExists + // Initialize the client + let client = try SearchClient(appID: "YOUR_APP_ID", apiKey: "YOUR_API_KEY") + + // Call the API + let response = try await client.indexExists(indexName: "") + // SEPARATOR< + } + + /// Snippet for the indexExists method. + /// + /// indexNotExists + func snippetForIndexExists1() async throws { + // >SEPARATOR indexExists indexNotExists + // Initialize the client + let client = try SearchClient(appID: "YOUR_APP_ID", apiKey: "YOUR_API_KEY") + + // Call the API + let response = try await client.indexExists(indexName: "") + // SEPARATOR< + } + + /// Snippet for the indexExists method. + /// + /// indexExistsWithError + func snippetForIndexExists2() async throws { + // >SEPARATOR indexExists indexExistsWithError + // Initialize the client + let client = try SearchClient(appID: "YOUR_APP_ID", apiKey: "YOUR_API_KEY") + + // Call the API + let response = try await client.indexExists(indexName: "") + // SEPARATOR< + } + /// Snippet for the listApiKeys method. /// /// listApiKeys diff --git a/specs/bundled/search.yml b/specs/bundled/search.yml index 59a6df6f88..dd4a3d2a77 100644 --- a/specs/bundled/search.yml +++ b/specs/bundled/search.yml @@ -3620,6 +3620,33 @@ paths: $ref: '#/components/schemas/batchResponse' '400': $ref: '#/components/responses/IndexNotFound' + /indexExists: + get: + x-helper: true + tags: + - search + operationId: indexExists + summary: Check if an index exists or not + description: > + You can initialize an index with any name. The index is created on + Algolia's servers when you add objects or set settings. To prevent + accidentally creating new indices, or changing existing indices, you can + use the exists method. The exists method returns a boolean that + indicates whether an initialized index has been created. + parameters: + - in: query + name: indexName + description: The name of the index to check. + required: true + schema: + type: string + responses: + '200': + description: Index exists. + content: + application/json: + schema: + type: boolean components: securitySchemes: appId: diff --git a/tests/output/csharp/src/generated/client/Abtesting.test.cs b/tests/output/csharp/src/generated/client/Abtesting.test.cs index b0131fb0d5..91574c6154 100644 --- a/tests/output/csharp/src/generated/client/Abtesting.test.cs +++ b/tests/output/csharp/src/generated/client/Abtesting.test.cs @@ -78,6 +78,7 @@ public async Task CommonApiTest3() public async Task ParametersTest0() { var client = new AbtestingClient(new AbtestingConfig("my-app-id", "my-api-key"), _echo); + await client.GetABTestAsync(123); EchoResponse result = _echo.LastResponse; @@ -88,6 +89,7 @@ public async Task ParametersTest0() public async Task ParametersTest1() { var client = new AbtestingClient(new AbtestingConfig("my-app-id", "my-api-key", "us"), _echo); + await client.GetABTestAsync(123); EchoResponse result = _echo.LastResponse; diff --git a/tests/output/csharp/src/generated/client/Analytics.test.cs b/tests/output/csharp/src/generated/client/Analytics.test.cs index f831672ba4..671b928a45 100644 --- a/tests/output/csharp/src/generated/client/Analytics.test.cs +++ b/tests/output/csharp/src/generated/client/Analytics.test.cs @@ -78,6 +78,7 @@ public async Task CommonApiTest3() public async Task ParametersTest0() { var client = new AnalyticsClient(new AnalyticsConfig("my-app-id", "my-api-key"), _echo); + await client.GetAverageClickPositionAsync("my-index"); EchoResponse result = _echo.LastResponse; @@ -88,6 +89,7 @@ public async Task ParametersTest0() public async Task ParametersTest1() { var client = new AnalyticsClient(new AnalyticsConfig("my-app-id", "my-api-key", "de"), _echo); + await client.CustomPostAsync("test"); EchoResponse result = _echo.LastResponse; diff --git a/tests/output/csharp/src/generated/client/Ingestion.test.cs b/tests/output/csharp/src/generated/client/Ingestion.test.cs index ea95d78311..f9171f1d61 100644 --- a/tests/output/csharp/src/generated/client/Ingestion.test.cs +++ b/tests/output/csharp/src/generated/client/Ingestion.test.cs @@ -78,6 +78,7 @@ public async Task CommonApiTest3() public async Task ParametersTest0() { var client = new IngestionClient(new IngestionConfig("my-app-id", "my-api-key", "us"), _echo); + await client.GetSourceAsync("6c02aeb1-775e-418e-870b-1faccd4b2c0f"); EchoResponse result = _echo.LastResponse; diff --git a/tests/output/csharp/src/generated/client/Insights.test.cs b/tests/output/csharp/src/generated/client/Insights.test.cs index 313dc71499..32f38c5bfe 100644 --- a/tests/output/csharp/src/generated/client/Insights.test.cs +++ b/tests/output/csharp/src/generated/client/Insights.test.cs @@ -78,6 +78,7 @@ public async Task CommonApiTest3() public async Task ParametersTest0() { var client = new InsightsClient(new InsightsConfig("my-app-id", "my-api-key"), _echo); + await client.PushEventsAsync( new InsightsEvents { @@ -109,6 +110,7 @@ await client.PushEventsAsync( public async Task ParametersTest1() { var client = new InsightsClient(new InsightsConfig("my-app-id", "my-api-key", "us"), _echo); + await client.CustomDeleteAsync("test"); EchoResponse result = _echo.LastResponse; diff --git a/tests/output/csharp/src/generated/client/Monitoring.test.cs b/tests/output/csharp/src/generated/client/Monitoring.test.cs index 4265dc34ae..7709d202c2 100644 --- a/tests/output/csharp/src/generated/client/Monitoring.test.cs +++ b/tests/output/csharp/src/generated/client/Monitoring.test.cs @@ -78,6 +78,7 @@ public async Task CommonApiTest3() public async Task ParametersTest0() { var client = new MonitoringClient(new MonitoringConfig("my-app-id", "my-api-key"), _echo); + await client.CustomDeleteAsync("test"); EchoResponse result = _echo.LastResponse; diff --git a/tests/output/csharp/src/generated/client/Recommend.test.cs b/tests/output/csharp/src/generated/client/Recommend.test.cs index cdfc1c2e01..66682e5244 100644 --- a/tests/output/csharp/src/generated/client/Recommend.test.cs +++ b/tests/output/csharp/src/generated/client/Recommend.test.cs @@ -30,6 +30,7 @@ public void Dispose() { } public async Task ApiTest0() { var client = new RecommendClient(new RecommendConfig("test-app-id", "test-api-key"), _echo); + await client.CustomGetAsync("test"); EchoResponse result = _echo.LastResponse; @@ -40,6 +41,7 @@ public async Task ApiTest0() public async Task ApiTest1() { var client = new RecommendClient(new RecommendConfig("test-app-id", "test-api-key"), _echo); + await client.CustomPostAsync("test"); EchoResponse result = _echo.LastResponse; diff --git a/tests/output/csharp/src/generated/client/Search.test.cs b/tests/output/csharp/src/generated/client/Search.test.cs index c6cf801850..0f3b1c30dc 100644 --- a/tests/output/csharp/src/generated/client/Search.test.cs +++ b/tests/output/csharp/src/generated/client/Search.test.cs @@ -30,6 +30,7 @@ public void Dispose() { } public async Task ApiTest0() { var client = new SearchClient(new SearchConfig("test-app-id", "test-api-key"), _echo); + await client.CustomGetAsync("test"); EchoResponse result = _echo.LastResponse; @@ -40,6 +41,7 @@ public async Task ApiTest0() public async Task ApiTest1() { var client = new SearchClient(new SearchConfig("test-app-id", "test-api-key"), _echo); + await client.CustomPostAsync("test"); EchoResponse result = _echo.LastResponse; @@ -287,6 +289,86 @@ public async Task GenerateSecuredApiKeyTest1() ); } + [Fact(DisplayName = "indexExists")] + public async Task IndexExistsTest0() + { + SearchConfig _config = new SearchConfig("test-app-id", "test-api-key") + { + CustomHosts = new List + { + new() + { + Scheme = HttpScheme.Http, + Url = "localhost", + Port = 6681, + Up = true, + LastUse = DateTime.UtcNow, + Accept = CallType.Read | CallType.Write, + } + } + }; + var client = new SearchClient(_config); + + var res = await client.IndexExistsAsync("indexExistsYES"); + + Assert.True(res); + } + + [Fact(DisplayName = "indexNotExists")] + public async Task IndexExistsTest1() + { + SearchConfig _config = new SearchConfig("test-app-id", "test-api-key") + { + CustomHosts = new List + { + new() + { + Scheme = HttpScheme.Http, + Url = "localhost", + Port = 6681, + Up = true, + LastUse = DateTime.UtcNow, + Accept = CallType.Read | CallType.Write, + } + } + }; + var client = new SearchClient(_config); + + var res = await client.IndexExistsAsync("indexExistsNO"); + + Assert.False(res); + } + + [Fact(DisplayName = "indexExistsWithError")] + public async Task IndexExistsTest2() + { + SearchConfig _config = new SearchConfig("test-app-id", "test-api-key") + { + CustomHosts = new List + { + new() + { + Scheme = HttpScheme.Http, + Url = "localhost", + Port = 6681, + Up = true, + LastUse = DateTime.UtcNow, + Accept = CallType.Read | CallType.Write, + } + } + }; + var client = new SearchClient(_config); + + _ex = await Assert.ThrowsAnyAsync(async () => + { + var res = await client.IndexExistsAsync("indexExistsERROR"); + }); + Assert.Equal( + "{\"message\":\"Invalid API key\"}".ToLowerInvariant(), + _ex.Message.ToLowerInvariant() + ); + } + [Fact(DisplayName = "client throws with invalid parameters")] public async Task ParametersTest0() { diff --git a/tests/output/csharp/src/generated/client/Usage.test.cs b/tests/output/csharp/src/generated/client/Usage.test.cs index 33a7f98abe..df73755f0e 100644 --- a/tests/output/csharp/src/generated/client/Usage.test.cs +++ b/tests/output/csharp/src/generated/client/Usage.test.cs @@ -30,6 +30,7 @@ public void Dispose() { } public async Task ApiTest0() { var client = new UsageClient(new UsageConfig("test-app-id", "test-api-key"), _echo); + await client.CustomGetAsync("test"); EchoResponse result = _echo.LastResponse; @@ -40,6 +41,7 @@ public async Task ApiTest0() public async Task ApiTest1() { var client = new UsageClient(new UsageConfig("test-app-id", "test-api-key"), _echo); + await client.CustomPostAsync("test"); EchoResponse result = _echo.LastResponse; diff --git a/tests/output/dart/test/client/insights_test.dart b/tests/output/dart/test/client/insights_test.dart index 4bf08b1f7b..cdb3b09a6d 100644 --- a/tests/output/dart/test/client/insights_test.dart +++ b/tests/output/dart/test/client/insights_test.dart @@ -92,7 +92,7 @@ void main() { apiKey: "my-api-key", options: ClientOptions(requester: requester)); requester.setOnRequest((request) { - expect(request.host.url, 'insights.algolia.io'); + expect(request.host.url, "insights.algolia.io"); }); try { final res = await client.pushEvents( @@ -131,7 +131,7 @@ void main() { region: 'us', options: ClientOptions(requester: requester)); requester.setOnRequest((request) { - expect(request.host.url, 'insights.us.algolia.io'); + expect(request.host.url, "insights.us.algolia.io"); }); try { final res = await client.customDelete( diff --git a/tests/output/dart/test/client/recommend_test.dart b/tests/output/dart/test/client/recommend_test.dart index 3dd77d08aa..f21ec5b5db 100644 --- a/tests/output/dart/test/client/recommend_test.dart +++ b/tests/output/dart/test/client/recommend_test.dart @@ -12,7 +12,7 @@ void main() { apiKey: "test-api-key", options: ClientOptions(requester: requester)); requester.setOnRequest((request) { - expect(request.host.url, 'test-app-id-dsn.algolia.net'); + expect(request.host.url, "test-app-id-dsn.algolia.net"); }); try { final res = await client.customGet( @@ -30,7 +30,7 @@ void main() { apiKey: "test-api-key", options: ClientOptions(requester: requester)); requester.setOnRequest((request) { - expect(request.host.url, 'test-app-id.algolia.net'); + expect(request.host.url, "test-app-id.algolia.net"); }); try { final res = await client.customPost( diff --git a/tests/output/dart/test/client/search_test.dart b/tests/output/dart/test/client/search_test.dart index 2a6bcec042..634e758163 100644 --- a/tests/output/dart/test/client/search_test.dart +++ b/tests/output/dart/test/client/search_test.dart @@ -12,7 +12,7 @@ void main() { apiKey: "test-api-key", options: ClientOptions(requester: requester)); requester.setOnRequest((request) { - expect(request.host.url, 'test-app-id-dsn.algolia.net'); + expect(request.host.url, "test-app-id-dsn.algolia.net"); }); try { final res = await client.customGet( @@ -30,7 +30,7 @@ void main() { apiKey: "test-api-key", options: ClientOptions(requester: requester)); requester.setOnRequest((request) { - expect(request.host.url, 'test-app-id.algolia.net'); + expect(request.host.url, "test-app-id.algolia.net"); }); try { final res = await client.customPost( diff --git a/tests/output/go/tests/client/search_test.go b/tests/output/go/tests/client/search_test.go index 5ad164b961..04d4b7c784 100644 --- a/tests/output/go/tests/client/search_test.go +++ b/tests/output/go/tests/client/search_test.go @@ -265,7 +265,7 @@ func TestSearchgenerateSecuredApiKey0(t *testing.T) { []string{"Movies"}), ) require.NoError(t, err) - require.Equal(t, `NjFhZmE0OGEyMTI3OThiODc0OTlkOGM0YjcxYzljY2M2NmU2NDE5ZWY0NDZjMWJhNjA2NzBkMjAwOTI2YWQyZnJlc3RyaWN0SW5kaWNlcz1Nb3ZpZXMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw`, res) + require.Equal(t, "NjFhZmE0OGEyMTI3OThiODc0OTlkOGM0YjcxYzljY2M2NmU2NDE5ZWY0NDZjMWJhNjA2NzBkMjAwOTI2YWQyZnJlc3RyaWN0SW5kaWNlcz1Nb3ZpZXMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw", res) } // generate secured api key with searchParams @@ -283,7 +283,84 @@ func TestSearchgenerateSecuredApiKey1(t *testing.T) { []string{"one", "two"})), ) require.NoError(t, err) - require.Equal(t, `MzAxMDUwYjYyODMxODQ3ZWM1ZDYzNTkxZmNjNDg2OGZjMjAzYjQyOTZhMGQ1NDJhMDFiNGMzYTYzODRhNmMxZWFyb3VuZFJhZGl1cz1hbGwmZmlsdGVycz1jYXRlZ29yeSUzQUJvb2slMjBPUiUyMGNhdGVnb3J5JTNBRWJvb2slMjBBTkQlMjBfdGFncyUzQXB1Ymxpc2hlZCZoaXRzUGVyUGFnZT0xMCZtb2RlPW5ldXJhbFNlYXJjaCZvcHRpb25hbFdvcmRzPW9uZSUyQ3R3byZxdWVyeT1iYXRtYW4mcmVzdHJpY3RJbmRpY2VzPU1vdmllcyUyQ2N0c19lMmVfc2V0dGluZ3MmcmVzdHJpY3RTb3VyY2VzPTE5Mi4xNjguMS4wJTJGMjQmdHlwb1RvbGVyYW5jZT1zdHJpY3QmdXNlclRva2VuPXVzZXIxMjMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw`, res) + require.Equal(t, "MzAxMDUwYjYyODMxODQ3ZWM1ZDYzNTkxZmNjNDg2OGZjMjAzYjQyOTZhMGQ1NDJhMDFiNGMzYTYzODRhNmMxZWFyb3VuZFJhZGl1cz1hbGwmZmlsdGVycz1jYXRlZ29yeSUzQUJvb2slMjBPUiUyMGNhdGVnb3J5JTNBRWJvb2slMjBBTkQlMjBfdGFncyUzQXB1Ymxpc2hlZCZoaXRzUGVyUGFnZT0xMCZtb2RlPW5ldXJhbFNlYXJjaCZvcHRpb25hbFdvcmRzPW9uZSUyQ3R3byZxdWVyeT1iYXRtYW4mcmVzdHJpY3RJbmRpY2VzPU1vdmllcyUyQ2N0c19lMmVfc2V0dGluZ3MmcmVzdHJpY3RTb3VyY2VzPTE5Mi4xNjguMS4wJTJGMjQmdHlwb1RvbGVyYW5jZT1zdHJpY3QmdXNlclRva2VuPXVzZXIxMjMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw", res) +} + +// indexExists +func TestSearchindexExists0(t *testing.T) { + var err error + var res any + _ = res + echo := &tests.EchoRequester{} + var client *search.APIClient + var cfg search.SearchConfiguration + _ = client + _ = echo + cfg = search.SearchConfiguration{ + Configuration: transport.Configuration{ + AppID: "test-app-id", + ApiKey: "test-api-key", + Hosts: []transport.StatefulHost{transport.NewStatefulHost("http", "localhost:6681", call.IsReadWrite)}, + }, + } + client, err = search.NewClientWithConfig(cfg) + require.NoError(t, err) + res, err = client.IndexExists( + "indexExistsYES", + ) + require.NoError(t, err) + require.Equal(t, true, res) +} + +// indexNotExists +func TestSearchindexExists1(t *testing.T) { + var err error + var res any + _ = res + echo := &tests.EchoRequester{} + var client *search.APIClient + var cfg search.SearchConfiguration + _ = client + _ = echo + cfg = search.SearchConfiguration{ + Configuration: transport.Configuration{ + AppID: "test-app-id", + ApiKey: "test-api-key", + Hosts: []transport.StatefulHost{transport.NewStatefulHost("http", "localhost:6681", call.IsReadWrite)}, + }, + } + client, err = search.NewClientWithConfig(cfg) + require.NoError(t, err) + res, err = client.IndexExists( + "indexExistsNO", + ) + require.NoError(t, err) + require.Equal(t, false, res) +} + +// indexExistsWithError +func TestSearchindexExists2(t *testing.T) { + var err error + var res any + _ = res + echo := &tests.EchoRequester{} + var client *search.APIClient + var cfg search.SearchConfiguration + _ = client + _ = echo + cfg = search.SearchConfiguration{ + Configuration: transport.Configuration{ + AppID: "test-app-id", + ApiKey: "test-api-key", + Hosts: []transport.StatefulHost{transport.NewStatefulHost("http", "localhost:6681", call.IsReadWrite)}, + }, + } + client, err = search.NewClientWithConfig(cfg) + require.NoError(t, err) + res, err = client.IndexExists( + "indexExistsERROR", + ) + require.EqualError(t, err, "API error [403] {\"message\":\"Invalid API key\"}") } // client throws with invalid parameters diff --git a/tests/output/java/build.gradle b/tests/output/java/build.gradle index ec9e5200fd..2594ac41f1 100644 --- a/tests/output/java/build.gradle +++ b/tests/output/java/build.gradle @@ -15,7 +15,12 @@ dependencies { testImplementation 'io.github.cdimascio:dotenv-java:3.0.1' } +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} + test() { + systemProperty "file.encoding", "UTF-8" useJUnitPlatform() testLogging { events "passed", "skipped", "failed" diff --git a/tests/output/java/src/test/java/com/algolia/client/Abtesting.test.java b/tests/output/java/src/test/java/com/algolia/client/Abtesting.test.java index 57868f4955..71fb029219 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Abtesting.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Abtesting.test.java @@ -88,7 +88,6 @@ void commonApiTest2() { client.customGet("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(5000, result.responseTimeout); } @@ -100,7 +99,6 @@ void commonApiTest3() { client.customPost("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(30000, result.responseTimeout); } @@ -111,7 +109,6 @@ void parametersTest0() { AbtestingClient client = new AbtestingClient("my-app-id", "my-api-key", withEchoRequester()); client.getABTest(123); EchoResponse result = echo.getLastResponse(); - assertEquals("analytics.algolia.com", result.host); } @@ -121,7 +118,6 @@ void parametersTest1() { AbtestingClient client = new AbtestingClient("my-app-id", "my-api-key", "us", withEchoRequester()); client.getABTest(123); EchoResponse result = echo.getLastResponse(); - assertEquals("analytics.us.algolia.com", result.host); } diff --git a/tests/output/java/src/test/java/com/algolia/client/Analytics.test.java b/tests/output/java/src/test/java/com/algolia/client/Analytics.test.java index 53cacab90d..d4121f58c3 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Analytics.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Analytics.test.java @@ -88,7 +88,6 @@ void commonApiTest2() { client.customGet("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(5000, result.responseTimeout); } @@ -100,7 +99,6 @@ void commonApiTest3() { client.customPost("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(30000, result.responseTimeout); } @@ -111,7 +109,6 @@ void parametersTest0() { AnalyticsClient client = new AnalyticsClient("my-app-id", "my-api-key", withEchoRequester()); client.getAverageClickPosition("my-index"); EchoResponse result = echo.getLastResponse(); - assertEquals("analytics.algolia.com", result.host); } @@ -121,7 +118,6 @@ void parametersTest1() { AnalyticsClient client = new AnalyticsClient("my-app-id", "my-api-key", "de", withEchoRequester()); client.customPost("test"); EchoResponse result = echo.getLastResponse(); - assertEquals("analytics.de.algolia.com", result.host); } diff --git a/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java b/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java index 2aaf23e6df..21b0b088bb 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java @@ -88,7 +88,6 @@ void commonApiTest2() { client.customGet("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(5000, result.responseTimeout); } @@ -100,7 +99,6 @@ void commonApiTest3() { client.customPost("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(30000, result.responseTimeout); } @@ -111,7 +109,6 @@ void parametersTest0() { IngestionClient client = new IngestionClient("my-app-id", "my-api-key", "us", withEchoRequester()); client.getSource("6c02aeb1-775e-418e-870b-1faccd4b2c0f"); EchoResponse result = echo.getLastResponse(); - assertEquals("data.us.algolia.com", result.host); } diff --git a/tests/output/java/src/test/java/com/algolia/client/Insights.test.java b/tests/output/java/src/test/java/com/algolia/client/Insights.test.java index 1fc1ba6be8..5853368430 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Insights.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Insights.test.java @@ -88,7 +88,6 @@ void commonApiTest2() { client.customGet("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(5000, result.responseTimeout); } @@ -100,7 +99,6 @@ void commonApiTest3() { client.customPost("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(30000, result.responseTimeout); } @@ -127,7 +125,6 @@ void parametersTest0() { ) ); EchoResponse result = echo.getLastResponse(); - assertEquals("insights.algolia.io", result.host); } @@ -137,7 +134,6 @@ void parametersTest1() { InsightsClient client = new InsightsClient("my-app-id", "my-api-key", "us", withEchoRequester()); client.customDelete("test"); EchoResponse result = echo.getLastResponse(); - assertEquals("insights.us.algolia.io", result.host); } diff --git a/tests/output/java/src/test/java/com/algolia/client/Monitoring.test.java b/tests/output/java/src/test/java/com/algolia/client/Monitoring.test.java index 7aae71f168..308ae7574d 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Monitoring.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Monitoring.test.java @@ -87,7 +87,6 @@ void commonApiTest2() { client.customGet("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(5000, result.responseTimeout); } @@ -99,7 +98,6 @@ void commonApiTest3() { client.customPost("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(30000, result.responseTimeout); } @@ -110,7 +108,6 @@ void parametersTest0() { MonitoringClient client = new MonitoringClient("my-app-id", "my-api-key", withEchoRequester()); client.customDelete("test"); EchoResponse result = echo.getLastResponse(); - assertEquals("status.algolia.com", result.host); } } diff --git a/tests/output/java/src/test/java/com/algolia/client/Personalization.test.java b/tests/output/java/src/test/java/com/algolia/client/Personalization.test.java index 85cfef3618..5ca01340a9 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Personalization.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Personalization.test.java @@ -88,7 +88,6 @@ void commonApiTest2() { client.customGet("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(5000, result.responseTimeout); } @@ -100,7 +99,6 @@ void commonApiTest3() { client.customPost("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(30000, result.responseTimeout); } diff --git a/tests/output/java/src/test/java/com/algolia/client/QuerySuggestions.test.java b/tests/output/java/src/test/java/com/algolia/client/QuerySuggestions.test.java index e13b9ff0c5..2b21f47989 100644 --- a/tests/output/java/src/test/java/com/algolia/client/QuerySuggestions.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/QuerySuggestions.test.java @@ -88,7 +88,6 @@ void commonApiTest2() { client.customGet("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(5000, result.responseTimeout); } @@ -100,7 +99,6 @@ void commonApiTest3() { client.customPost("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(30000, result.responseTimeout); } diff --git a/tests/output/java/src/test/java/com/algolia/client/Recommend.test.java b/tests/output/java/src/test/java/com/algolia/client/Recommend.test.java index 7a941f1beb..bcaed5ed41 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Recommend.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Recommend.test.java @@ -50,7 +50,6 @@ void apiTest0() { RecommendClient client = new RecommendClient("test-app-id", "test-api-key", withEchoRequester()); client.customGet("test"); EchoResponse result = echo.getLastResponse(); - assertEquals("test-app-id-dsn.algolia.net", result.host); } @@ -60,7 +59,6 @@ void apiTest1() { RecommendClient client = new RecommendClient("test-app-id", "test-api-key", withEchoRequester()); client.customPost("test"); EchoResponse result = echo.getLastResponse(); - assertEquals("test-app-id.algolia.net", result.host); } @@ -107,7 +105,6 @@ void commonApiTest2() { client.customGet("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(5000, result.responseTimeout); } @@ -119,7 +116,6 @@ void commonApiTest3() { client.customPost("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(30000, result.responseTimeout); } diff --git a/tests/output/java/src/test/java/com/algolia/client/Search.test.java b/tests/output/java/src/test/java/com/algolia/client/Search.test.java index d747de9d7d..c65c0f14af 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Search.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Search.test.java @@ -54,7 +54,6 @@ void apiTest0() { SearchClient client = new SearchClient("test-app-id", "test-api-key", withEchoRequester()); client.customGet("test"); EchoResponse result = echo.getLastResponse(); - assertEquals("test-app-id-dsn.algolia.net", result.host); } @@ -64,7 +63,6 @@ void apiTest1() { SearchClient client = new SearchClient("test-app-id", "test-api-key", withEchoRequester()); client.customPost("test"); EchoResponse result = echo.getLastResponse(); - assertEquals("test-app-id.algolia.net", result.host); } @@ -171,7 +169,6 @@ void commonApiTest2() { client.customGet("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(5000, result.responseTimeout); } @@ -183,7 +180,6 @@ void commonApiTest3() { client.customPost("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(30000, result.responseTimeout); } @@ -255,6 +251,54 @@ void generateSecuredApiKeyTest1() { }); } + @Test + @DisplayName("indexExists") + void indexExistsTest0() { + assertDoesNotThrow(() -> { + SearchClient client = new SearchClient( + "test-app-id", + "test-api-key", + withCustomHosts(Arrays.asList(new Host("localhost", EnumSet.of(CallType.READ, CallType.WRITE), "http", 6681)), false) + ); + var res = client.indexExists("indexExistsYES"); + + assertEquals(true, res); + }); + } + + @Test + @DisplayName("indexNotExists") + void indexExistsTest1() { + assertDoesNotThrow(() -> { + SearchClient client = new SearchClient( + "test-app-id", + "test-api-key", + withCustomHosts(Arrays.asList(new Host("localhost", EnumSet.of(CallType.READ, CallType.WRITE), "http", 6681)), false) + ); + var res = client.indexExists("indexExistsNO"); + + assertEquals(false, res); + }); + } + + @Test + @DisplayName("indexExistsWithError") + void indexExistsTest2() { + assertDoesNotThrow(() -> { + SearchClient client = new SearchClient( + "test-app-id", + "test-api-key", + withCustomHosts(Arrays.asList(new Host("localhost", EnumSet.of(CallType.READ, CallType.WRITE), "http", 6681)), false) + ); + { + Exception exception = assertThrows(Exception.class, () -> { + var res = client.indexExists("indexExistsERROR"); + }); + assertEquals("Status Code: 403 - {\"message\":\"Invalid API key\"}", exception.getMessage()); + } + }); + } + @Test @DisplayName("client throws with invalid parameters") void parametersTest0() { diff --git a/tests/output/java/src/test/java/com/algolia/client/Usage.test.java b/tests/output/java/src/test/java/com/algolia/client/Usage.test.java index 185e6f41a6..30c36cf842 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Usage.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Usage.test.java @@ -51,7 +51,6 @@ void apiTest0() { UsageClient client = new UsageClient("test-app-id", "test-api-key", withEchoRequester()); client.customGet("test"); EchoResponse result = echo.getLastResponse(); - assertEquals("usage.algolia.com", result.host); } @@ -61,7 +60,6 @@ void apiTest1() { UsageClient client = new UsageClient("test-app-id", "test-api-key", withEchoRequester()); client.customPost("test"); EchoResponse result = echo.getLastResponse(); - assertEquals("usage.algolia.com", result.host); } @@ -108,7 +106,6 @@ void commonApiTest2() { client.customGet("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(5000, result.responseTimeout); } @@ -120,7 +117,6 @@ void commonApiTest3() { client.customPost("1/test"); EchoResponse result = echo.getLastResponse(); - assertEquals(2000, result.connectTimeout); assertEquals(30000, result.responseTimeout); } diff --git a/tests/output/javascript/src/client/search.test.ts b/tests/output/javascript/src/client/search.test.ts index 11a27a14ad..a29dd07863 100644 --- a/tests/output/javascript/src/client/search.test.ts +++ b/tests/output/javascript/src/client/search.test.ts @@ -150,6 +150,41 @@ describe('generateSecuredApiKey', () => { }, 15000); }); +describe('indexExists', () => { + test('indexExists', async () => { + const client = searchClient('test-app-id', 'test-api-key', { + hosts: [{ url: 'localhost', port: 6681, accept: 'readWrite', protocol: 'http' }], + }); + + const result = await client.indexExists({ indexName: 'indexExistsYES' }); + + expect(result).toEqual(true); + }, 15000); + + test('indexNotExists', async () => { + const client = searchClient('test-app-id', 'test-api-key', { + hosts: [{ url: 'localhost', port: 6681, accept: 'readWrite', protocol: 'http' }], + }); + + const result = await client.indexExists({ indexName: 'indexExistsNO' }); + + expect(result).toEqual(false); + }, 15000); + + test('indexExistsWithError', async () => { + const client = searchClient('test-app-id', 'test-api-key', { + hosts: [{ url: 'localhost', port: 6681, accept: 'readWrite', protocol: 'http' }], + }); + + try { + const result = await client.indexExists({ indexName: 'indexExistsERROR' }); + throw new Error('test is expected to throw error'); + } catch (e) { + expect((e as Error).message).toMatch('Invalid API key'); + } + }, 15000); +}); + describe('parameters', () => { test('client throws with invalid parameters', async () => { try { @@ -383,7 +418,7 @@ describe('waitForApiKey', () => { const result = await client.waitForApiKey({ key: 'api-key-delete-operation-test-javascript', operation: 'delete' }); - expect(result).toBeUndefined(); + expect(result).toEqual(); }, 15000); }); diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/benchmark/SearchTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/benchmark/SearchTest.kt index 07ce58ead8..2af50df129 100644 --- a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/benchmark/SearchTest.kt +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/benchmark/SearchTest.kt @@ -32,6 +32,8 @@ class SearchTest { ), ) }, + intercept = { + }, ) } } diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/SearchTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/SearchTest.kt index 920840acdd..0b2d999749 100644 --- a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/SearchTest.kt +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/SearchTest.kt @@ -198,7 +198,7 @@ class SearchTest { }, response = { - assertEquals("""NjFhZmE0OGEyMTI3OThiODc0OTlkOGM0YjcxYzljY2M2NmU2NDE5ZWY0NDZjMWJhNjA2NzBkMjAwOTI2YWQyZnJlc3RyaWN0SW5kaWNlcz1Nb3ZpZXMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw""", it) + assertEquals("NjFhZmE0OGEyMTI3OThiODc0OTlkOGM0YjcxYzljY2M2NmU2NDE5ZWY0NDZjMWJhNjA2NzBkMjAwOTI2YWQyZnJlc3RyaWN0SW5kaWNlcz1Nb3ZpZXMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw", it) }, ) @@ -230,12 +230,56 @@ class SearchTest { }, response = { - assertEquals("""MzAxMDUwYjYyODMxODQ3ZWM1ZDYzNTkxZmNjNDg2OGZjMjAzYjQyOTZhMGQ1NDJhMDFiNGMzYTYzODRhNmMxZWFyb3VuZFJhZGl1cz1hbGwmZmlsdGVycz1jYXRlZ29yeSUzQUJvb2slMjBPUiUyMGNhdGVnb3J5JTNBRWJvb2slMjBBTkQlMjBfdGFncyUzQXB1Ymxpc2hlZCZoaXRzUGVyUGFnZT0xMCZtb2RlPW5ldXJhbFNlYXJjaCZvcHRpb25hbFdvcmRzPW9uZSUyQ3R3byZxdWVyeT1iYXRtYW4mcmVzdHJpY3RJbmRpY2VzPU1vdmllcyUyQ2N0c19lMmVfc2V0dGluZ3MmcmVzdHJpY3RTb3VyY2VzPTE5Mi4xNjguMS4wJTJGMjQmdHlwb1RvbGVyYW5jZT1zdHJpY3QmdXNlclRva2VuPXVzZXIxMjMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw""", it) + assertEquals("MzAxMDUwYjYyODMxODQ3ZWM1ZDYzNTkxZmNjNDg2OGZjMjAzYjQyOTZhMGQ1NDJhMDFiNGMzYTYzODRhNmMxZWFyb3VuZFJhZGl1cz1hbGwmZmlsdGVycz1jYXRlZ29yeSUzQUJvb2slMjBPUiUyMGNhdGVnb3J5JTNBRWJvb2slMjBBTkQlMjBfdGFncyUzQXB1Ymxpc2hlZCZoaXRzUGVyUGFnZT0xMCZtb2RlPW5ldXJhbFNlYXJjaCZvcHRpb25hbFdvcmRzPW9uZSUyQ3R3byZxdWVyeT1iYXRtYW4mcmVzdHJpY3RJbmRpY2VzPU1vdmllcyUyQ2N0c19lMmVfc2V0dGluZ3MmcmVzdHJpY3RTb3VyY2VzPTE5Mi4xNjguMS4wJTJGMjQmdHlwb1RvbGVyYW5jZT1zdHJpY3QmdXNlclRva2VuPXVzZXIxMjMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw", it) }, ) } + @Test + fun `indexExists`() = runTest { + val client = SearchClient(appId = "test-app-id", apiKey = "test-api-key", options = ClientOptions(hosts = listOf(Host(url = "localhost", protocol = "http", port = 6681)))) + client.runTest( + call = { + indexExists( + indexName = "indexExistsYES", + ) + }, + + response = { + assertEquals(true, it) + }, + + ) + } + + @Test + fun `indexNotExists`() = runTest { + val client = SearchClient(appId = "test-app-id", apiKey = "test-api-key", options = ClientOptions(hosts = listOf(Host(url = "localhost", protocol = "http", port = 6681)))) + client.runTest( + call = { + indexExists( + indexName = "indexExistsNO", + ) + }, + + response = { + assertEquals(false, it) + }, + + ) + } + + @Test + fun `indexExistsWithError`() = runTest { + val client = SearchClient(appId = "test-app-id", apiKey = "test-api-key", options = ClientOptions(hosts = listOf(Host(url = "localhost", protocol = "http", port = 6681)))) + assertFails { + client.indexExists( + indexName = "indexExistsERROR", + ) + }.let { error -> assertError(error, "Client request(GET http://localhost:6681/1/indexes/indexExistsERROR/settings) invalid: 403 Forbidden. Text: \"{\"message\":\"Invalid API key\"}\"") } + } + @Test fun `client throws with invalid parameters`() = runTest { assertFails { diff --git a/tests/output/php/src/client/SearchTest.php b/tests/output/php/src/client/SearchTest.php index b27d4e8fc3..bcbd3b7bb3 100644 --- a/tests/output/php/src/client/SearchTest.php +++ b/tests/output/php/src/client/SearchTest.php @@ -240,6 +240,49 @@ public function test1generateSecuredApiKey() ); } + #[TestDox('indexExists')] + public function test0indexExists() + { + $client = SearchClient::createWithConfig(SearchConfig::create('test-app-id', 'test-api-key')->setFullHosts(['http://localhost:6681'])); + + $res = $client->indexExists( + 'indexExistsYES', + ); + $this->assertEquals( + true, + $res + ); + } + + #[TestDox('indexNotExists')] + public function test1indexExists() + { + $client = SearchClient::createWithConfig(SearchConfig::create('test-app-id', 'test-api-key')->setFullHosts(['http://localhost:6681'])); + + $res = $client->indexExists( + 'indexExistsNO', + ); + $this->assertEquals( + false, + $res + ); + } + + #[TestDox('indexExistsWithError')] + public function test2indexExists() + { + $client = SearchClient::createWithConfig(SearchConfig::create('test-app-id', 'test-api-key')->setFullHosts(['http://localhost:6681'])); + + try { + $res = $client->indexExists( + 'indexExistsERROR', + ); + $this->fail('Expected exception to be thrown'); + } catch (\Exception $e) { + $this->assertEquals($e->getMessage(), 'Invalid API key'); + } + } + #[TestDox('client throws with invalid parameters')] public function test0parameters() { @@ -546,7 +589,10 @@ public function test2waitForApiKey() 'api-key-delete-operation-test-php', 'delete', ); - $this->assertNull($res); + $this->assertEquals( + null, + $res + ); } #[TestDox('wait for an application-level task')] diff --git a/tests/output/python/tests/client/search_test.py b/tests/output/python/tests/client/search_test.py index d02b1cf92d..812001f337 100644 --- a/tests/output/python/tests/client/search_test.py +++ b/tests/output/python/tests/client/search_test.py @@ -180,7 +180,7 @@ async def test_generate_secured_api_key_0(self): ) assert ( _req - == """NjFhZmE0OGEyMTI3OThiODc0OTlkOGM0YjcxYzljY2M2NmU2NDE5ZWY0NDZjMWJhNjA2NzBkMjAwOTI2YWQyZnJlc3RyaWN0SW5kaWNlcz1Nb3ZpZXMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw""" + == "NjFhZmE0OGEyMTI3OThiODc0OTlkOGM0YjcxYzljY2M2NmU2NDE5ZWY0NDZjMWJhNjA2NzBkMjAwOTI2YWQyZnJlc3RyaWN0SW5kaWNlcz1Nb3ZpZXMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw" ) async def test_generate_secured_api_key_1(self): @@ -215,9 +215,57 @@ async def test_generate_secured_api_key_1(self): ) assert ( _req - == """MzAxMDUwYjYyODMxODQ3ZWM1ZDYzNTkxZmNjNDg2OGZjMjAzYjQyOTZhMGQ1NDJhMDFiNGMzYTYzODRhNmMxZWFyb3VuZFJhZGl1cz1hbGwmZmlsdGVycz1jYXRlZ29yeSUzQUJvb2slMjBPUiUyMGNhdGVnb3J5JTNBRWJvb2slMjBBTkQlMjBfdGFncyUzQXB1Ymxpc2hlZCZoaXRzUGVyUGFnZT0xMCZtb2RlPW5ldXJhbFNlYXJjaCZvcHRpb25hbFdvcmRzPW9uZSUyQ3R3byZxdWVyeT1iYXRtYW4mcmVzdHJpY3RJbmRpY2VzPU1vdmllcyUyQ2N0c19lMmVfc2V0dGluZ3MmcmVzdHJpY3RTb3VyY2VzPTE5Mi4xNjguMS4wJTJGMjQmdHlwb1RvbGVyYW5jZT1zdHJpY3QmdXNlclRva2VuPXVzZXIxMjMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw""" + == "MzAxMDUwYjYyODMxODQ3ZWM1ZDYzNTkxZmNjNDg2OGZjMjAzYjQyOTZhMGQ1NDJhMDFiNGMzYTYzODRhNmMxZWFyb3VuZFJhZGl1cz1hbGwmZmlsdGVycz1jYXRlZ29yeSUzQUJvb2slMjBPUiUyMGNhdGVnb3J5JTNBRWJvb2slMjBBTkQlMjBfdGFncyUzQXB1Ymxpc2hlZCZoaXRzUGVyUGFnZT0xMCZtb2RlPW5ldXJhbFNlYXJjaCZvcHRpb25hbFdvcmRzPW9uZSUyQ3R3byZxdWVyeT1iYXRtYW4mcmVzdHJpY3RJbmRpY2VzPU1vdmllcyUyQ2N0c19lMmVfc2V0dGluZ3MmcmVzdHJpY3RTb3VyY2VzPTE5Mi4xNjguMS4wJTJGMjQmdHlwb1RvbGVyYW5jZT1zdHJpY3QmdXNlclRva2VuPXVzZXIxMjMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw" ) + async def test_index_exists_0(self): + """ + indexExists + """ + + _config = SearchConfig("test-app-id", "test-api-key") + _config.hosts = HostsCollection( + [Host(url="localhost", scheme="http", port=6681)] + ) + self._client = SearchClient.create_with_config(config=_config) + _req = await self._client.index_exists( + index_name="indexExistsYES", + ) + assert _req is True + + async def test_index_exists_1(self): + """ + indexNotExists + """ + + _config = SearchConfig("test-app-id", "test-api-key") + _config.hosts = HostsCollection( + [Host(url="localhost", scheme="http", port=6681)] + ) + self._client = SearchClient.create_with_config(config=_config) + _req = await self._client.index_exists( + index_name="indexExistsNO", + ) + assert _req is False + + async def test_index_exists_2(self): + """ + indexExistsWithError + """ + + _config = SearchConfig("test-app-id", "test-api-key") + _config.hosts = HostsCollection( + [Host(url="localhost", scheme="http", port=6681)] + ) + self._client = SearchClient.create_with_config(config=_config) + try: + await self._client.index_exists( + index_name="indexExistsERROR", + ) + assert False + except (ValueError, Exception) as e: + assert str(e) == "Invalid API key" + async def test_parameters_0(self): """ client throws with invalid parameters diff --git a/tests/output/ruby/test/client/search_test.rb b/tests/output/ruby/test/client/search_test.rb index 7bfc379a17..c98b0e770b 100644 --- a/tests/output/ruby/test/client/search_test.rb +++ b/tests/output/ruby/test/client/search_test.rb @@ -241,6 +241,73 @@ def test_generate_secured_api_key1 ) end + # indexExists + def test_index_exists0 + client = Algolia::SearchClient.create_with_config( + Algolia::Configuration.new( + "test-app-id", + "test-api-key", + [ + Algolia::Transport::StatefulHost.new( + "localhost", + protocol: "http://", + port: 6681, + accept: CallType::READ | CallType::WRITE + ) + ], + "searchClient" + ) + ) + req = client.index_exists?("indexExistsYES") + assert_equal(true, req) + end + + # indexNotExists + def test_index_exists1 + client = Algolia::SearchClient.create_with_config( + Algolia::Configuration.new( + "test-app-id", + "test-api-key", + [ + Algolia::Transport::StatefulHost.new( + "localhost", + protocol: "http://", + port: 6681, + accept: CallType::READ | CallType::WRITE + ) + ], + "searchClient" + ) + ) + req = client.index_exists?("indexExistsNO") + assert_equal(false, req) + end + + # indexExistsWithError + def test_index_exists2 + client = Algolia::SearchClient.create_with_config( + Algolia::Configuration.new( + "test-app-id", + "test-api-key", + [ + Algolia::Transport::StatefulHost.new( + "localhost", + protocol: "http://", + port: 6681, + accept: CallType::READ | CallType::WRITE + ) + ], + "searchClient" + ) + ) + begin + client.index_exists?("indexExistsERROR") + assert(false, "An error should have been raised") + rescue => e + assert_equal("Invalid API key", e.message) + end + end + # client throws with invalid parameters def test_parameters0 begin @@ -575,7 +642,7 @@ def test_wait_for_api_key2 ) ) req = client.wait_for_api_key("api-key-delete-operation-test-ruby", "delete") - assert_nil(req) + assert_equal(nil, req) end # wait for an application-level task diff --git a/tests/output/swift/Tests/client/SearchTests.swift b/tests/output/swift/Tests/client/SearchTests.swift index f7509a472a..7cfb90b899 100644 --- a/tests/output/swift/Tests/client/SearchTests.swift +++ b/tests/output/swift/Tests/client/SearchTests.swift @@ -192,10 +192,7 @@ final class SearchClientClientTests: XCTestCase { let response = try await client.deleteObjects(indexName: "cts_e2e_deleteObjects_swift", objectIDs: ["1", "2"]) let comparableData = try XCTUnwrap("[{\"taskID\":666,\"objectIDs\":[\"1\",\"2\"]}]".data(using: .utf8)) - try XCTLenientAssertEqual( - received: CodableHelper.jsonEncoder.encode(response), - expected: comparableData - ) + try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) } /// generate secured api key basic @@ -246,6 +243,52 @@ final class SearchClientClientTests: XCTestCase { ) } + /// indexExists + func testIndexExistsTest0() async throws { + let configuration = try SearchClientConfiguration( + appID: "test-app-id", + apiKey: "test-api-key", + hosts: [RetryableHost(url: URL(string: "http://localhost:6681")!)] + ) + let transporter = Transporter(configuration: configuration) + let client = SearchClient(configuration: configuration, transporter: transporter) + let response = try await client.indexExists(indexName: "indexExistsYES") + + XCTAssertEqual(true, response) + } + + /// indexNotExists + func testIndexExistsTest1() async throws { + let configuration = try SearchClientConfiguration( + appID: "test-app-id", + apiKey: "test-api-key", + hosts: [RetryableHost(url: URL(string: "http://localhost:6681")!)] + ) + let transporter = Transporter(configuration: configuration) + let client = SearchClient(configuration: configuration, transporter: transporter) + let response = try await client.indexExists(indexName: "indexExistsNO") + + XCTAssertEqual(false, response) + } + + /// indexExistsWithError + func testIndexExistsTest2() async throws { + let configuration = try SearchClientConfiguration( + appID: "test-app-id", + apiKey: "test-api-key", + hosts: [RetryableHost(url: URL(string: "http://localhost:6681")!)] + ) + let transporter = Transporter(configuration: configuration) + let client = SearchClient(configuration: configuration, transporter: transporter) + do { + let response = try await client.indexExists(indexName: "indexExistsERROR") + + XCTFail("Expected an error to be thrown") + } catch { + XCTAssertEqual(error.localizedDescription, "HTTP error: Status code: 403 Message: Invalid API key") + } + } + /// client throws with invalid parameters func testParametersTest0() async throws { do { @@ -307,10 +350,7 @@ final class SearchClientClientTests: XCTestCase { ) let comparableData = try XCTUnwrap("[{\"taskID\":444,\"objectIDs\":[\"1\",\"2\"]}]".data(using: .utf8)) - try XCTLenientAssertEqual( - received: CodableHelper.jsonEncoder.encode(response), - expected: comparableData - ) + try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) } /// call partialUpdateObjects with createIfNotExists=false @@ -329,10 +369,7 @@ final class SearchClientClientTests: XCTestCase { ) let comparableData = try XCTUnwrap("[{\"taskID\":555,\"objectIDs\":[\"3\",\"4\"]}]".data(using: .utf8)) - try XCTLenientAssertEqual( - received: CodableHelper.jsonEncoder.encode(response), - expected: comparableData - ) + try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) } /// call replaceAllObjects without error @@ -366,10 +403,7 @@ final class SearchClientClientTests: XCTestCase { "{\"copyOperationResponse\":{\"taskID\":125,\"updatedAt\":\"2021-01-01T00:00:00.000Z\"},\"batchResponses\":[{\"taskID\":127,\"objectIDs\":[\"1\",\"2\",\"3\"]},{\"taskID\":130,\"objectIDs\":[\"4\",\"5\",\"6\"]},{\"taskID\":133,\"objectIDs\":[\"7\",\"8\",\"9\"]},{\"taskID\":134,\"objectIDs\":[\"10\"]}],\"moveOperationResponse\":{\"taskID\":777,\"updatedAt\":\"2021-01-01T00:00:00.000Z\"}}" .data(using: .utf8) ) - try XCTLenientAssertEqual( - received: CodableHelper.jsonEncoder.encode(response), - expected: comparableData - ) + try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) } /// call saveObjects without error @@ -387,10 +421,7 @@ final class SearchClientClientTests: XCTestCase { ) let comparableData = try XCTUnwrap("[{\"taskID\":333,\"objectIDs\":[\"1\",\"2\"]}]".data(using: .utf8)) - try XCTLenientAssertEqual( - received: CodableHelper.jsonEncoder.encode(response), - expected: comparableData - ) + try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) } /// saveObjects should report errors @@ -436,10 +467,7 @@ final class SearchClientClientTests: XCTestCase { "{\"value\":\"api-key-add-operation-test-swift\",\"description\":\"my new api key\",\"acl\":[\"search\",\"addObject\"],\"validity\":300,\"maxQueriesPerIPPerHour\":100,\"maxHitsPerQuery\":20,\"createdAt\":1720094400}" .data(using: .utf8) ) - try XCTLenientAssertEqual( - received: CodableHelper.jsonEncoder.encode(response), - expected: comparableData - ) + try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) } /// wait for api key - update @@ -470,10 +498,7 @@ final class SearchClientClientTests: XCTestCase { "{\"value\":\"api-key-update-operation-test-swift\",\"description\":\"my updated api key\",\"acl\":[\"search\",\"addObject\",\"deleteObject\"],\"indexes\":[\"Movies\",\"Books\"],\"referers\":[\"*google.com\",\"*algolia.com\"],\"validity\":305,\"maxQueriesPerIPPerHour\":95,\"maxHitsPerQuery\":20,\"createdAt\":1720094400}" .data(using: .utf8) ) - try XCTLenientAssertEqual( - received: CodableHelper.jsonEncoder.encode(response), - expected: comparableData - ) + try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) } /// wait for api key - delete @@ -505,10 +530,7 @@ final class SearchClientClientTests: XCTestCase { let response = try await client.waitForAppTask(taskID: Int64(123)) let comparableData = try XCTUnwrap("{\"status\":\"published\"}".data(using: .utf8)) - try XCTLenientAssertEqual( - received: CodableHelper.jsonEncoder.encode(response), - expected: comparableData - ) + try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) } /// wait for task @@ -523,9 +545,6 @@ final class SearchClientClientTests: XCTestCase { let response = try await client.waitForTask(indexName: "wait-task-swift", taskID: Int64(123)) let comparableData = try XCTUnwrap("{\"status\":\"published\"}".data(using: .utf8)) - try XCTLenientAssertEqual( - received: CodableHelper.jsonEncoder.encode(response), - expected: comparableData - ) + try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) } }