diff --git a/clients/algoliasearch-client-csharp/algoliasearch/Utils/SearchClientExtensions.cs b/clients/algoliasearch-client-csharp/algoliasearch/Utils/SearchClientExtensions.cs index 474d29713e..cbd2d7ddf0 100644 --- a/clients/algoliasearch-client-csharp/algoliasearch/Utils/SearchClientExtensions.cs +++ b/clients/algoliasearch-client-csharp/algoliasearch/Utils/SearchClientExtensions.cs @@ -593,4 +593,24 @@ private static async Task> CreateIterable(Func> execut return responses; } + + public bool Exists(string indexName, CancellationToken cancellationToken = default) => AsyncHelper.RunSync(() => IndexExistsAsync(indexName, cancellationToken)); + + public async Task IndexExistsAsync(string indexName, CancellationToken cancellationToken = default) + { + try + { + await GetSettingsAsync(indexName, null, cancellationToken); + } + catch (AlgoliaApiException ex) when (ex.HttpErrorCode == 404) + { + return await Task.FromResult(false); + } + catch (Exception ex) + { + throw ex; + } + + return await Task.FromResult(true); + } } diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/extensions/SearchClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/extensions/SearchClient.kt index a3c743d679..282680a3fe 100644 --- a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/extensions/SearchClient.kt +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/extensions/SearchClient.kt @@ -521,3 +521,16 @@ public fun securedApiKeyRemainingValidity(apiKey: String): Duration { val validUntil = Instant.fromEpochMilliseconds(match.groupValues[1].toLong()) return validUntil - Clock.System.now() } + +public suspend fun SearchClient.indexExists(indexName: String): Boolean { + try { + getSettings(indexName) + } catch (e: AlgoliaApiException) { + if (e.httpErrorCode == 404) { + return false + } + throw e + } + + return true +} diff --git a/clients/algoliasearch-client-scala/src/main/scala/algoliasearch/extension/package.scala b/clients/algoliasearch-client-scala/src/main/scala/algoliasearch/extension/package.scala index 371eecb653..80781732ee 100644 --- a/clients/algoliasearch-client-scala/src/main/scala/algoliasearch/extension/package.scala +++ b/clients/algoliasearch-client-scala/src/main/scala/algoliasearch/extension/package.scala @@ -395,5 +395,16 @@ package object extension { moveOperationResponse = move ) } + + def indexExists(indexName: String)(implicit ec: ExecutionContext): Future[Boolean] = { + try { + client.getSettings(indexName) + } catch { + case apiError: AlgoliaApiException if apiError.httpErrorCode == 404 => Future.successful(false) + case e: Throwable => throw e + } + + Future.successful(true) + } } } diff --git a/clients/algoliasearch-client-swift/Sources/Search/Extra/SearchClientExtension.swift b/clients/algoliasearch-client-swift/Sources/Search/Extra/SearchClientExtension.swift index e8100f96f8..5862dc8f57 100644 --- a/clients/algoliasearch-client-swift/Sources/Search/Extra/SearchClientExtension.swift +++ b/clients/algoliasearch-client-swift/Sources/Search/Extra/SearchClientExtension.swift @@ -541,7 +541,7 @@ public extension SearchClient { batchSize: Int = 1000, requestOptions: RequestOptions? = nil ) async throws -> ReplaceAllObjectsResponse { - let tmpIndexName = try "\(indexName)_tmp_\(Int.random(in: 1_000_000 ..< 10_000_000))" + let tmpIndexName = "\(indexName)_tmp_\(Int.random(in: 1_000_000 ..< 10_000_000))" var copyOperationResponse = try await operationIndex( indexName: indexName, @@ -627,4 +627,14 @@ public extension SearchClient { return timestampDate.timeIntervalSince1970 - Date().timeIntervalSince1970 } + + func indexExists(indexName: String) async throws -> Bool { + do { + _ = try await self.getSettings(indexName: indexName) + } catch let AlgoliaError.httpError(error) where error.statusCode == 404 { + return false + } + + return true + } } diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java b/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java index 1a76d6b1a3..a9941cd56c 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java @@ -32,6 +32,20 @@ public void enhanceParameters(Map parameters, Map enhanceParameter(Object param) throws CTSException, JsonMappingException, JsonProcessingException { + Map testOutput = createDefaultOutput(); + testOutput.put("isRoot", true); + if (param == null) { + handleNull(null, testOutput); + } else if (param instanceof List || param instanceof Map) { + testOutput.put("isString", true); + testOutput.put("value", Json.mapper().writeValueAsString(param)); + } else { + handlePrimitive(param, testOutput, null); + } + return testOutput; + } + /** * @param parameters The object to traverse and annotate with type * @param bundle The output object @@ -214,13 +228,15 @@ private Map createDefaultOutput() { testOutput.put("isSimpleObject", false); testOutput.put("oneOfModel", false); testOutput.put("isAdditionalProperty", false); + testOutput.put("isPrimitive", false); return testOutput; } private void handleNull(IJsonSchemaValidationProperties spec, Map testOutput) { + testOutput.put("isPrimitive", true); testOutput.put("isNull", true); - if (spec.getIsModel() || spec instanceof CodegenModel) { + if (spec != null && (spec.getIsModel() || spec instanceof CodegenModel)) { testOutput.put("isNullObject", true); } } @@ -458,6 +474,7 @@ private void handlePrimitive(Object param, Map testOutput, IJson testOutput.put("isAnyType", true); } } + testOutput.put("isPrimitive", true); testOutput.put("value", param); } @@ -522,6 +539,11 @@ private String getObjectNameForLanguage(String objectName) { } private String inferDataType(Object param, CodegenParameter spec, Map output) throws CTSException { + if (param == null) { + if (spec != null) spec.setIsNull(true); + if (output != null) output.put("isNull", true); + return "null"; + } switch (param.getClass().getSimpleName()) { case "String": if (spec != null) spec.setIsString(true); diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsClient.java b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsClient.java index f713153d41..727c80ae5c 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsClient.java +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsClient.java @@ -3,7 +3,6 @@ import com.algolia.codegen.cts.manager.CTSManager; import com.algolia.codegen.exceptions.CTSException; import com.algolia.codegen.utils.*; -import io.swagger.util.Json; import java.io.File; import java.util.ArrayList; import java.util.HashMap; @@ -112,6 +111,7 @@ public void run(Map models, Map stepOut.put("isGeneric", (boolean) ope.vendorExtensions.getOrDefault("x-is-generic", false)); if (ope.returnType != null && ope.returnType.length() > 0) { stepOut.put("returnType", Helpers.toPascalCase(ope.returnType)); + stepOut.put("returnsBoolean", ope.returnType.equals("Boolean")); // ruby requires a ? for boolean functions. } // set on testOut because we need to wrap everything for java. @@ -149,6 +149,9 @@ public void run(Map models, Map break; case "timeouts": stepOut.put("testTimeouts", true); + Map timeouts = (Map) step.expected.match; + stepOut.put("matchConnectTimeout", timeouts.get("connectTimeout")); + stepOut.put("matchResponseTimeout", timeouts.get("responseTimeout")); break; case "response": stepOut.put("testResponse", true); @@ -172,24 +175,8 @@ public void run(Map models, Map ((String) stepOut.get("expectedError")).replace(step.method, Helpers.toPascalCase(step.method)) ); } - } else if (step.expected.match != null) { - Map matchMap = new HashMap<>(); - if (step.expected.match instanceof Map match) { - paramsType.enhanceParameters(match, matchMap); - stepOut.put("match", matchMap); - stepOut.put("matchIsJSON", true); - } else if (step.expected.match instanceof List match) { - matchMap.put("parameters", Json.mapper().writeValueAsString(step.expected.match)); - stepOut.put("match", matchMap); - stepOut.put("matchIsJSON", true); - } else { - stepOut.put("match", step.expected.match); - } - } else if (step.expected.match == null) { - stepOut.put("match", Map.of()); - stepOut.put("matchIsJSON", false); - stepOut.put("matchIsNull", true); } + stepOut.put("match", paramsType.enhanceParameter(step.expected.match)); } steps.add(stepOut); } diff --git a/scripts/cli/index.ts b/scripts/cli/index.ts index 35a6264ad6..69bf487a94 100644 --- a/scripts/cli/index.ts +++ b/scripts/cli/index.ts @@ -40,6 +40,11 @@ const flags = { program.name('cli'); +program.hook('preAction', () => { + // restore the cursor because sometime it's broken + process.stdout.write('\x1B[?25h'); +}); + program .command('generate') .description('Generate a specified client') diff --git a/scripts/cts/testServer/waitFor.ts b/scripts/cts/testServer/waitFor.ts index 3222c1df66..9e3eb7d949 100644 --- a/scripts/cts/testServer/waitFor.ts +++ b/scripts/cts/testServer/waitFor.ts @@ -125,6 +125,21 @@ function addRoutes(app: Express): void { status: 'published', }); }); + + app.get('/1/indexes/:indexName/settings', (req, res) => { + if (req.params.indexName === 'indexExistsYES') { + res.status(200).json({ + attributesForFaceting: ['searchable(brand)'], + searchableAttributes: ['name', 'brand'], + customRanking: ['desc(price)', 'asc(name)'], + replicas: ['indexExistsYES-1', 'indexExistsYES-2'], + }); + } else if (req.params.indexName === 'indexExistsNO') { + res.status(404).json({ message: 'Index not found' }); + } else { + res.status(403).json({ message: 'Invalid API key' }); + } + }); } export function waitForApiKeyServer(): Promise { diff --git a/scripts/formatter.ts b/scripts/formatter.ts index 9ea748f4cc..e58d5ba221 100644 --- a/scripts/formatter.ts +++ b/scripts/formatter.ts @@ -45,7 +45,7 @@ export async function formatter(language: string, cwd: string): Promise { case 'php': await runComposerInstall(); await run( - `PHP_CS_FIXER_IGNORE_ENV=1 php clients/algoliasearch-client-php/vendor/bin/php-cs-fixer fix ${cwd} --rules=@PhpCsFixer --using-cache=no --allow-risky=yes`, + `php clients/algoliasearch-client-php/vendor/bin/php-cs-fixer fix ${cwd} --rules=@PhpCsFixer --using-cache=no --allow-risky=yes`, { language }, ); break; diff --git a/specs/search/helpers/indexExists.yml b/specs/search/helpers/indexExists.yml new file mode 100644 index 0000000000..15c3d06f8f --- /dev/null +++ b/specs/search/helpers/indexExists.yml @@ -0,0 +1,23 @@ +method: + get: + x-helper: true + tags: + - Index + 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 diff --git a/specs/search/spec.yml b/specs/search/spec.yml index fb72c59207..50e7c73c55 100644 --- a/specs/search/spec.yml +++ b/specs/search/spec.yml @@ -387,3 +387,6 @@ paths: /partialUpdateObjects: $ref: 'helpers/partialUpdateObjects.yml#/method' + + /indexExists: + $ref: 'helpers/indexExists.yml#/method' diff --git a/templates/csharp/tests/client/tests.mustache b/templates/csharp/tests/client/tests.mustache index c19b39683a..232c779a44 100644 --- a/templates/csharp/tests/client/tests.mustache +++ b/templates/csharp/tests/client/tests.mustache @@ -16,32 +16,25 @@ {{/isError}} {{^isError}} {{#dynamicTemplate}}{{/dynamicTemplate}} - {{#match}} - {{#testUserAgent}} { - var regexp = new Regex("{{#lambda.escapeSlash}}{{{match}}}{{/lambda.escapeSlash}}"); - Assert.Matches(regexp,result.Headers["user-agent"]); - }{{/testUserAgent}} - {{#testTimeouts}} - Assert.Equal({{{match.parametersWithDataTypeMap.connectTimeout.value}}}, result.ConnectTimeout.TotalMilliseconds); - Assert.Equal({{{match.parametersWithDataTypeMap.responseTimeout.value}}}, result.ResponseTimeout.TotalMilliseconds); - {{/testTimeouts}} - {{#testHost}} - Assert.Equal("{{{match}}}", result.Host); - {{/testHost}} - {{#testResponse}} - {{#matchIsJSON}} - JsonAssert.EqualOverrideDefault("{{#lambda.escapeQuotes}}{{{match.parameters}}}{{/lambda.escapeQuotes}}", JsonSerializer.Serialize(res, JsonConfig.Options), new JsonDiffConfig(false)); - {{/matchIsJSON}} - {{^matchIsJSON}} - {{#matchIsNull}} - Assert.Null(res); - {{/matchIsNull}} - {{^matchIsNull}} - Assert.Equal("{{{match}}}", res); - {{/matchIsNull}} - {{/matchIsJSON}} - {{/testResponse}} - {{/match}} + {{#testUserAgent}} { + var regexp = new Regex({{#match}}{{> tests/generateParams}}{{/match}}); + Assert.Matches(regexp,result.Headers["user-agent"]); + }{{/testUserAgent}} + {{#testTimeouts}} + Assert.Equal({{{matchConnectTimeout}}}, result.ConnectTimeout.TotalMilliseconds); + Assert.Equal({{{matchResponseTimeout}}}, result.ResponseTimeout.TotalMilliseconds); + {{/testTimeouts}} + {{#testHost}} + Assert.Equal({{#match}}{{> tests/generateParams}}{{/match}}, result.Host); + {{/testHost}} + {{#testResponse}} + {{#match.isPrimitive}} + Assert.Equal({{#match}}{{> tests/generateParams}}{{/match}}, res); + {{/match.isPrimitive}} + {{^match.isPrimitive}} + JsonAssert.EqualOverrideDefault({{#match}}{{> tests/generateParams}}{{/match}}, JsonSerializer.Serialize(res, JsonConfig.Options), new JsonDiffConfig(false)); + {{/match.isPrimitive}} + {{/testResponse}} {{/isError}} {{#times}} } diff --git a/templates/csharp/tests/generateInnerParams.mustache b/templates/csharp/tests/generateInnerParams.mustache index 650aa701cc..87f7bfb6a9 100644 --- a/templates/csharp/tests/generateInnerParams.mustache +++ b/templates/csharp/tests/generateInnerParams.mustache @@ -2,7 +2,7 @@ null {{/isNull}} {{#isString}} - "{{{value}}}" + "{{#lambda.escapeQuotes}}{{#lambda.escapeSlash}}{{{value}}}{{/lambda.escapeSlash}}{{/lambda.escapeQuotes}}" {{/isString}} {{#isInteger}} {{{value}}} diff --git a/templates/dart/tests/client/client.mustache b/templates/dart/tests/client/client.mustache index 995315a89b..c333e0f5e3 100644 --- a/templates/dart/tests/client/client.mustache +++ b/templates/dart/tests/client/client.mustache @@ -36,10 +36,10 @@ void main() { TestHandle.current.markSkipped('User agent added using an interceptor'); {{/testUserAgent}} {{#testTimeouts}} - expect({{{match.parametersWithDataTypeMap.responseTimeout.value}}}, request.timeout.inMilliseconds); + expect({{{matchResponseTimeout}}}, request.timeout.inMilliseconds); {{/testTimeouts}} {{#testHost}} - expect(request.host.url, '{{{match}}}'); + expect(request.host.url, {{#match}}{{> tests/param_value}}{{/match}}); {{/testHost}} }); {{/match}} diff --git a/templates/dart/tests/client/method.mustache b/templates/dart/tests/client/method.mustache index 8778089cce..15baf9e21e 100644 --- a/templates/dart/tests/client/method.mustache +++ b/templates/dart/tests/client/method.mustache @@ -4,16 +4,14 @@ try { {{> tests/request_param}} {{/parametersWithDataType}} ); - {{#match}} {{#testResponse}} - {{#matchIsJSON}} - expectBody(res, """{{{match.parameters}}}"""); - {{/matchIsJSON}} - {{^matchIsJSON}} - expect(res, """{{match}}"""); - {{/matchIsJSON}} + {{^match.isPrimitive}} + expectBody(res, """{{{match.value}}}"""); + {{/match.isPrimitive}} + {{#match.isPrimitive}} + expect(res, {{#match}}{{> tests/param_value}}{{/match}}); + {{/match.isPrimitive}} {{/testResponse}} - {{/match}} } on InterceptionException catch (_) { // Ignore InterceptionException } \ No newline at end of file diff --git a/templates/go/search_helpers.mustache b/templates/go/search_helpers.mustache index 65d96e8767..0845019265 100644 --- a/templates/go/search_helpers.mustache +++ b/templates/go/search_helpers.mustache @@ -690,4 +690,21 @@ func (c *APIClient) ReplaceAllObjects(indexName string, objects []map[string]any BatchResponses: batchResp, 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 } \ No newline at end of file diff --git a/templates/go/tests/client/tests.mustache b/templates/go/tests/client/tests.mustache index 0fe7f135c1..3834085ea7 100644 --- a/templates/go/tests/client/tests.mustache +++ b/templates/go/tests/client/tests.mustache @@ -25,33 +25,31 @@ func Test{{#lambda.titlecase}}{{clientPrefix}}{{testType}}{{/lambda.titlecase}}{ {{^isError}} {{#dynamicTemplate}}{{/dynamicTemplate}} require.NoError(t, err) - {{#match}} - {{#testUserAgent}} - require.Regexp(t, regexp.MustCompile(`{{{match}}}`), echo.Header.Get("User-Agent")) - {{/testUserAgent}} - {{#testTimeouts}} - require.Equal(t, int64({{{match.parametersWithDataTypeMap.connectTimeout.value}}}), echo.ConnectTimeout.Milliseconds()) - require.Equal(t, int64({{{match.parametersWithDataTypeMap.responseTimeout.value}}}), echo.Timeout.Milliseconds()) - {{/testTimeouts}} - {{#testHost}} - require.Equal(t, "{{{match}}}", echo.Host) - {{/testHost}} - {{#testResponse}} - {{#matchIsJSON}} - rawBody, err := json.Marshal(res) - require.NoError(t, err) - require.JSONEq(t, `{{{match.parameters}}}`, string(rawBody)) - {{/matchIsJSON}} - {{^matchIsJSON}} - {{#matchIsNull}} - require.Nil(t, res) - {{/matchIsNull}} - {{^matchIsNull}} - require.Equal(t, `{{{match}}}`, res) - {{/matchIsNull}} - {{/matchIsJSON}} - {{/testResponse}} - {{/match}} + {{#testUserAgent}} + require.Regexp(t, regexp.MustCompile(`{{{match.value}}}`), echo.Header.Get("User-Agent")) + {{/testUserAgent}} + {{#testTimeouts}} + require.Equal(t, int64({{{matchConnectTimeout}}}), echo.ConnectTimeout.Milliseconds()) + require.Equal(t, int64({{{matchResponseTimeout}}}), echo.Timeout.Milliseconds()) + {{/testTimeouts}} + {{#testHost}} + require.Equal(t, "{{{match.value}}}", echo.Host) + {{/testHost}} + {{#testResponse}} + {{#match.isPrimitive}} + {{#match.isNull}} + require.Nil(t, res) + {{/match.isNull}} + {{^match.isNull}} + require.Equal(t, {{#match}}{{> tests/generateParams}}{{/match}}, res) + {{/match.isNull}} + {{/match.isPrimitive}} + {{^match.isPrimitive}} + rawBody, err := json.Marshal(res) + require.NoError(t, err) + require.JSONEq(t, `{{{match.value}}}`, string(rawBody)) + {{/match.isPrimitive}} + {{/testResponse}} {{/isError}} {{#times}} } diff --git a/templates/java/api_helpers.mustache b/templates/java/api_helpers.mustache index a04a651067..ea8117e8e5 100644 --- a/templates/java/api_helpers.mustache +++ b/templates/java/api_helpers.mustache @@ -862,4 +862,16 @@ long timeStamp = Long.parseLong(validUntilMatch.replace("validUntil=", "")); 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; +} {{/isSearchClient}} \ No newline at end of file diff --git a/templates/java/tests/build.mustache b/templates/java/tests/build.mustache index 739fe47162..0171074647 100644 --- a/templates/java/tests/build.mustache +++ b/templates/java/tests/build.mustache @@ -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/templates/java/tests/client/tests.mustache b/templates/java/tests/client/tests.mustache index e0e1146c2d..1a1abece5a 100644 --- a/templates/java/tests/client/tests.mustache +++ b/templates/java/tests/client/tests.mustache @@ -21,32 +21,27 @@ void {{testType}}Test{{testIndex}}() { {{/isError}} {{^isError}} {{#dynamicTemplate}}{{/dynamicTemplate}} - {{#match}} - {{#testUserAgent}} { - String regexp = "{{#lambda.escapeSlash}}{{{match}}}{{/lambda.escapeSlash}}"; - assertTrue(result.headers.get("user-agent").matches(regexp), "Expected " + result.headers.get("user-agent") + " to match the following regex: " + regexp); - }{{/testUserAgent}} - {{#testTimeouts}} - assertEquals({{{match.parametersWithDataTypeMap.connectTimeout.value}}}, result.connectTimeout); - assertEquals({{{match.parametersWithDataTypeMap.responseTimeout.value}}}, result.responseTimeout); - {{/testTimeouts}} - {{#testHost}} - assertEquals("{{{match}}}", result.host); - {{/testHost}} - {{#testResponse}} - {{#matchIsJSON}} - assertDoesNotThrow(() -> JSONAssert.assertEquals("{{#lambda.escapeQuotes}}{{{match.parameters}}}{{/lambda.escapeQuotes}}", json.writeValueAsString(res), JSONCompareMode.STRICT)); - {{/matchIsJSON}} - {{^matchIsJSON}} - {{#matchIsNull}} - assertEquals(null, res); - {{/matchIsNull}} - {{^matchIsNull}} - assertEquals("{{{match}}}", res); - {{/matchIsNull}} - {{/matchIsJSON}} - {{/testResponse}} - {{/match}} + {{#testUserAgent}} + { + String regexp = {{#match}}{{> tests/generateParams}}{{/match}}; + assertTrue(result.headers.get("user-agent").matches(regexp), "Expected " + result.headers.get("user-agent") + " to match the following regex: " + regexp); + } + {{/testUserAgent}} + {{#testTimeouts}} + assertEquals({{{matchConnectTimeout}}}, result.connectTimeout); + assertEquals({{{matchResponseTimeout}}}, result.responseTimeout); + {{/testTimeouts}} + {{#testHost}} + assertEquals({{#match}}{{> tests/generateParams}}{{/match}}, result.host); + {{/testHost}} + {{#testResponse}} + {{#match.isPrimitive}} + assertEquals({{#match}}{{> tests/generateParams}}{{/match}}, res); + {{/match.isPrimitive}} + {{^match.isPrimitive}} + assertDoesNotThrow(() -> JSONAssert.assertEquals({{#match}}{{> tests/generateParams}}{{/match}}, json.writeValueAsString(res), JSONCompareMode.STRICT)); + {{/match.isPrimitive}} + {{/testResponse}} {{/isError}} {{#times}} } diff --git a/templates/java/tests/generateInnerParams.mustache b/templates/java/tests/generateInnerParams.mustache index 99a284e7bd..308030cbf8 100644 --- a/templates/java/tests/generateInnerParams.mustache +++ b/templates/java/tests/generateInnerParams.mustache @@ -2,7 +2,7 @@ null {{/isNull}} {{#isString}} - "{{{value}}}" + "{{#lambda.escapeQuotes}}{{#lambda.escapeSlash}}{{{value}}}{{/lambda.escapeSlash}}{{/lambda.escapeQuotes}}" {{/isString}} {{#isInteger}} {{{value}}} diff --git a/templates/javascript/clients/client/api/helpers.mustache b/templates/javascript/clients/client/api/helpers.mustache index 043d664d68..06c7d7869c 100644 --- a/templates/javascript/clients/client/api/helpers.mustache +++ b/templates/javascript/clients/client/api/helpers.mustache @@ -448,6 +448,19 @@ async replaceAllObjects( 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; +}, {{/isAlgoliasearchClient}} /** diff --git a/templates/javascript/clients/client/api/imports.mustache b/templates/javascript/clients/client/api/imports.mustache index d1da078a33..8d22018ed5 100644 --- a/templates/javascript/clients/client/api/imports.mustache +++ b/templates/javascript/clients/client/api/imports.mustache @@ -4,6 +4,7 @@ import { getAlgoliaAgent, shuffle, {{#isSearchClient}} + ApiError, serializeQueryParameters, createIterablePromise, {{/isSearchClient}} @@ -16,7 +17,6 @@ import type { Request, RequestOptions, {{#isSearchClient}} - ApiError, IterableOptions, {{/isSearchClient}} } from '@algolia/client-common'; diff --git a/templates/javascript/tests/client/tests.mustache b/templates/javascript/tests/client/tests.mustache index f61be2192d..905c51a4a7 100644 --- a/templates/javascript/tests/client/tests.mustache +++ b/templates/javascript/tests/client/tests.mustache @@ -22,26 +22,26 @@ describe('{{testType}}', () => { {{#dynamicTemplate}}{{/dynamicTemplate}} {{#testUserAgent}} - expect(decodeURIComponent(result.algoliaAgent)).toMatch(/{{{match}}}/); + expect(decodeURIComponent(result.algoliaAgent)).toMatch(/{{{match.value}}}/); {{/testUserAgent}} {{#testTimeouts}} - expect(result).toEqual(expect.objectContaining({{{match.parameters}}})); + expect(result).toEqual(expect.objectContaining({{{match.value}}})); {{/testTimeouts}} {{#testHost}} - expect(result.host).toEqual("{{{match}}}"); + expect(result.host).toEqual("{{{match.value}}}"); {{/testHost}} {{#testResponse}} - {{#matchIsJSON}} - expect(result).toEqual({{{match.parameters}}}); - {{/matchIsJSON}} - {{^matchIsJSON}} - {{#matchIsNull}} - expect(result).toBeUndefined(); - {{/matchIsNull}} - {{^matchIsNull}} - expect(result).toEqual("{{{match}}}"); - {{/matchIsNull}} - {{/matchIsJSON}} + {{#match.isPrimitive}} + {{#match.isString}} + expect(result).toEqual("{{{match.value}}}"); + {{/match.isString}} + {{^match.isString}} + expect(result).toEqual({{{match.value}}}); + {{/match.isString}} + {{/match.isPrimitive}} + {{^match.isPrimitive}} + expect(result).toEqual({{{match.value}}}); + {{/match.isPrimitive}} {{/testResponse}} {{/isError}} {{#times}} diff --git a/templates/kotlin/tests/client/tests.mustache b/templates/kotlin/tests/client/tests.mustache index 3b2eaaa256..5be4b6e026 100644 --- a/templates/kotlin/tests/client/tests.mustache +++ b/templates/kotlin/tests/client/tests.mustache @@ -22,42 +22,40 @@ fun `{{#lambda.replaceBacktick}}{{{testName}}}{{/lambda.replaceBacktick}}`() = r call = { {{> tests/method}} }, - {{#match}} {{^testResponse}} intercept = { {{#testUserAgent}} - val regexp = "{{#lambda.escapeSlash}}{{{match}}}{{/lambda.escapeSlash}}".toRegex() + val regexp = {{#match}}{{> tests/param_value}}{{/match}}.toRegex() val header = it.headers["User-Agent"].orEmpty() assertTrue(actual = header.matches(regexp), message = "Expected $header to match the following regex: $regexp") {{/testUserAgent}} {{#testTimeouts}} - assertEquals({{{match.parametersWithDataTypeMap.connectTimeout.value}}}, it.connectTimeout); - assertEquals({{{match.parametersWithDataTypeMap.responseTimeout.value}}}, it.socketTimeout); + assertEquals({{{matchConnectTimeout}}}, it.connectTimeout); + assertEquals({{{matchResponseTimeout}}}, it.socketTimeout); {{/testTimeouts}} {{#testHost}} - assertEquals("{{{match}}}", it.url.host); + assertEquals({{#match}}{{> tests/param_value}}{{/match}}, it.url.host); {{/testHost}} }{{/testResponse}}{{#testResponse}} {{#isHelper}}response = { - {{#matchIsJSON}} + {{^match.isPrimitive}} assertNotNull(it) - JSONAssert.assertEquals("""{{{match.parameters}}}""", Json.encodeToString(Json.encodeToJsonElement(it)), JSONCompareMode.STRICT) - {{/matchIsJSON}} - {{^matchIsJSON}} - {{#matchIsNull}} + JSONAssert.assertEquals("""{{{match.value}}}""", Json.encodeToString(Json.encodeToJsonElement(it)), JSONCompareMode.STRICT) + {{/match.isPrimitive}} + {{#match.isPrimitive}} + {{#match.isNull}} assertNull(it) - {{/matchIsNull}} - {{^matchIsNull}} - assertEquals("""{{{match}}}""", it) - {{/matchIsNull}} - {{/matchIsJSON}} + {{/match.isNull}} + {{^match.isNull}} + assertEquals({{#match}}{{> tests/param_value}}{{/match}}, it) + {{/match.isNull}} + {{/match.isPrimitive}} }{{/isHelper}} {{^isHelper}}response = { val response = Json.encodeToString(it) - assertEquals("{{#lambda.escapeQuotes}}{{{match.parameters}}}{{/lambda.escapeQuotes}}", response) + assertEquals({{#match}}{{> tests/param_value}}{{/match}}, response) }{{/isHelper}} {{/testResponse}} - {{/match}} ) {{/isMethod}} {{/isError}} diff --git a/templates/kotlin/tests/method.mustache b/templates/kotlin/tests/method.mustache index 7e48ff21c6..8104a289bf 100644 --- a/templates/kotlin/tests/method.mustache +++ b/templates/kotlin/tests/method.mustache @@ -14,7 +14,7 @@ {{#requestOptions.headers}} headers = buildMap { {{#parametersWithDataType}} - put("{{{key}}}", {{> tests/param_value}}) + put("{{{key}}}", {{> tests/param_value}}) {{/parametersWithDataType}} }, {{/requestOptions.headers}} diff --git a/templates/kotlin/tests/param_list.mustache b/templates/kotlin/tests/param_list.mustache index b9896bd612..3f11638c99 100644 --- a/templates/kotlin/tests/param_list.mustache +++ b/templates/kotlin/tests/param_list.mustache @@ -1 +1 @@ -{{#oneOfModel}}{{{parentClassName}}}.of{{#x-one-of-explicit-name}}{{{type}}}{{/x-one-of-explicit-name}}(listOf({{#value}}{{> tests/param_value}}{{/value}})){{/oneOfModel}}{{^oneOfModel}}listOf({{#value}}{{> tests/param_value}}{{/value}}){{/oneOfModel}} \ No newline at end of file +{{#oneOfModel}}{{{parentClassName}}}.of{{#x-one-of-explicit-name}}{{{type}}}{{/x-one-of-explicit-name}}(listOf({{#value}}{{> tests/param_value}},{{/value}})){{/oneOfModel}}{{^oneOfModel}}listOf({{#value}}{{> tests/param_value}},{{/value}}){{/oneOfModel}} \ No newline at end of file diff --git a/templates/kotlin/tests/param_map.mustache b/templates/kotlin/tests/param_map.mustache index 237dc8ee22..af6624fd11 100644 --- a/templates/kotlin/tests/param_map.mustache +++ b/templates/kotlin/tests/param_map.mustache @@ -1 +1 @@ -mapOf({{#value}} "{{key}}" to {{> tests/param_value}}{{/value}}) \ No newline at end of file +mapOf({{#value}} "{{key}}" to {{> tests/param_value}},{{/value}}) \ No newline at end of file diff --git a/templates/kotlin/tests/param_value.mustache b/templates/kotlin/tests/param_value.mustache index 76c4c02be0..f9e007d4b0 100644 --- a/templates/kotlin/tests/param_value.mustache +++ b/templates/kotlin/tests/param_value.mustache @@ -1 +1 @@ -{{#isNull}}empty(),{{/isNull}}{{#isString}}{{#oneOfModel}}{{{parentClassName}}}.of("{{{value}}}"){{/oneOfModel}}{{^oneOfModel}}"{{{value}}}"{{/oneOfModel}},{{/isString}}{{#isInteger}}{{#oneOfModel}}{{{parentClassName}}}.of({{{value}}}){{/oneOfModel}}{{^oneOfModel}}{{{value}}}{{/oneOfModel}},{{/isInteger}}{{#isLong}}{{#oneOfModel}}{{{parentClassName}}}.of({{{value}}}L){{/oneOfModel}}{{^oneOfModel}}{{{value}}}L{{/oneOfModel}},{{/isLong}}{{#isDouble}}{{#oneOfModel}}{{{parentClassName}}}.of({{{value}}}){{/oneOfModel}}{{^oneOfModel}}{{{value}}}{{/oneOfModel}},{{/isDouble}}{{#isBoolean}}{{#oneOfModel}}{{{parentClassName}}}.of({{{value}}}){{/oneOfModel}}{{^oneOfModel}}{{{value}}}{{/oneOfModel}},{{/isBoolean}}{{#isEnum}}{{{objectName}}}.entries.first { it.value == "{{{value}}}" },{{/isEnum}}{{#isArray}}{{> tests/param_list}},{{/isArray}}{{#isObject}}{{> tests/param_object}},{{/isObject}}{{#isFreeFormObject}}{{#isSimpleObject}}{{> tests/param_json_object}},{{/isSimpleObject}}{{^isSimpleObject}}{{#isAnyType}}{{> tests/param_json_any}},{{/isAnyType}}{{^isAnyType}}{{> tests/param_map}},{{/isAnyType}}{{/isSimpleObject}}{{/isFreeFormObject}} \ No newline at end of file +{{#isNull}}empty(){{/isNull}}{{#isString}}{{#oneOfModel}}{{{parentClassName}}}.of("{{{value}}}"){{/oneOfModel}}{{^oneOfModel}}"{{#lambda.escapeQuotes}}{{#lambda.escapeSlash}}{{{value}}}{{/lambda.escapeSlash}}{{/lambda.escapeQuotes}}"{{/oneOfModel}}{{/isString}}{{#isInteger}}{{#oneOfModel}}{{{parentClassName}}}.of({{{value}}}){{/oneOfModel}}{{^oneOfModel}}{{{value}}}{{/oneOfModel}}{{/isInteger}}{{#isLong}}{{#oneOfModel}}{{{parentClassName}}}.of({{{value}}}L){{/oneOfModel}}{{^oneOfModel}}{{{value}}}L{{/oneOfModel}}{{/isLong}}{{#isDouble}}{{#oneOfModel}}{{{parentClassName}}}.of({{{value}}}){{/oneOfModel}}{{^oneOfModel}}{{{value}}}{{/oneOfModel}}{{/isDouble}}{{#isBoolean}}{{#oneOfModel}}{{{parentClassName}}}.of({{{value}}}){{/oneOfModel}}{{^oneOfModel}}{{{value}}}{{/oneOfModel}}{{/isBoolean}}{{#isEnum}}{{{objectName}}}.entries.first { it.value == "{{{value}}}" }{{/isEnum}}{{#isArray}}{{> tests/param_list}}{{/isArray}}{{#isObject}}{{> tests/param_object}}{{/isObject}}{{#isFreeFormObject}}{{#isSimpleObject}}{{> tests/param_json_object}}{{/isSimpleObject}}{{^isSimpleObject}}{{#isAnyType}}{{> tests/param_json_any}}{{/isAnyType}}{{^isAnyType}}{{> tests/param_map}}{{/isAnyType}}{{/isSimpleObject}}{{/isFreeFormObject}} \ No newline at end of file diff --git a/templates/kotlin/tests/request_param.mustache b/templates/kotlin/tests/request_param.mustache index d0dbc23e20..0146bf2f78 100644 --- a/templates/kotlin/tests/request_param.mustache +++ b/templates/kotlin/tests/request_param.mustache @@ -1 +1 @@ -{{^hasAdditionalProperties}}{{#lambda.camelcase}}{{{key}}}{{/lambda.camelcase}} = {{> tests/param_value}}{{/hasAdditionalProperties}}{{#hasAdditionalProperties}}{{> tests/param_value}}{{/hasAdditionalProperties}} \ No newline at end of file +{{^hasAdditionalProperties}}{{#lambda.camelcase}}{{{key}}}{{/lambda.camelcase}} = {{> tests/param_value}},{{/hasAdditionalProperties}}{{#hasAdditionalProperties}}{{> tests/param_value}},{{/hasAdditionalProperties}} \ No newline at end of file diff --git a/templates/php/api.mustache b/templates/php/api.mustache index f9bf10ebe2..1f74590fa6 100644 --- a/templates/php/api.mustache +++ b/templates/php/api.mustache @@ -17,6 +17,8 @@ use {{invokerPackage}}\RetryStrategy\ApiWrapperInterface; use {{invokerPackage}}\RetryStrategy\ClusterHosts; use {{invokerPackage}}\Support\Helpers; +use Algolia\AlgoliaSearch\Exceptions\NotFoundException; + /** * {{classname}} Class Doc Comment * @@ -645,6 +647,19 @@ use {{invokerPackage}}\Support\Helpers; return $validUntil - time(); } + + public function indexExists($indexName) + { + try { + $this->getSettings($indexName); + } catch (NotFoundException $e) { + return false; + } catch (Exception $e) { + throw $e; + } + + return true; + } {{/isSearchClient}} private function sendRequest($method, $resourcePath, $headers, $queryParameters, $httpBody, $requestOptions, $useReadTransporter = false) diff --git a/templates/php/tests/client/tests.mustache b/templates/php/tests/client/tests.mustache index 5e7414cd22..923f57352a 100644 --- a/templates/php/tests/client/tests.mustache +++ b/templates/php/tests/client/tests.mustache @@ -19,52 +19,45 @@ public function test{{testIndex}}{{testType}}() {{/isError}} {{^isError}} {{#dynamicTemplate}}{{/dynamicTemplate}} - {{#match}} - {{#testUserAgent}} - $this->assertTrue( - (bool) preg_match( - '/{{#lambda.escapeSlash}}{{{match}}}{{/lambda.escapeSlash}}/', - $this->recordedRequest['request']->getHeader('User-Agent')[0] - ) - ); - {{/testUserAgent}} - {{#testHost}} - $this->assertEquals( - '{{{match}}}', - $this->recordedRequest['request']->getUri()->getHost() - ); - {{/testHost}} - {{#testTimeouts}} + {{#testUserAgent}} + $this->assertTrue( + (bool) preg_match( + '/{{{match.value}}}/', + $this->recordedRequest['request']->getHeader('User-Agent')[0] + ) + ); + {{/testUserAgent}} + {{#testHost}} + $this->assertEquals( + {{#match}}{{> tests/generateParams}}{{/match}} + $this->recordedRequest['request']->getUri()->getHost() + ); + {{/testHost}} + {{#testTimeouts}} + $this->assertEquals( + {{{matchConnectTimeout}}}, + $this->recordedRequest['connectTimeout'] + ); + + $this->assertEquals( + {{{matchResponseTimeout}}}, + $this->recordedRequest['responseTimeout'] + ); + {{/testTimeouts}} + {{#testResponse}} + {{^match.isPrimitive}} $this->assertEquals( - {{{match.parametersWithDataTypeMap.connectTimeout.value}}}, - $this->recordedRequest['connectTimeout'] + '{{{match.value}}}', + json_encode($res) ); - + {{/match.isPrimitive}} + {{#match.isPrimitive}} $this->assertEquals( - {{{match.parametersWithDataTypeMap.responseTimeout.value}}}, - $this->recordedRequest['responseTimeout'] + {{#match}}{{> tests/generateParams}}{{/match}} + $res ); - {{/testTimeouts}} - {{#testResponse}} - {{#matchIsJSON}} - $this->assertEquals( - '{{{match.parameters}}}', - json_encode($res) - ); - {{/matchIsJSON}} - {{^matchIsJSON}} - {{#matchIsNull}} - $this->assertNull($res); - {{/matchIsNull}} - {{^matchIsNull}} - $this->assertEquals( - '{{{match}}}', - $res - ); - {{/matchIsNull}} - {{/matchIsJSON}} - {{/testResponse}} - {{/match}} + {{/match.isPrimitive}} + {{/testResponse}} {{/isError}} {{#times}} } diff --git a/templates/php/tests/generateParams.mustache b/templates/php/tests/generateParams.mustache index 814384c3cc..2265d6e214 100644 --- a/templates/php/tests/generateParams.mustache +++ b/templates/php/tests/generateParams.mustache @@ -3,7 +3,7 @@ null, {{/isNull}} {{#isString}} - "{{{value}}}", + "{{#lambda.escapeSlash}}{{{value}}}{{/lambda.escapeSlash}}", {{/isString}} {{#isEnum}} "{{{value}}}", @@ -33,4 +33,4 @@ {{^isAnyType}} [{{#value}}{{> tests/generateParams}}{{/value}}], {{/isAnyType}} -{{/isFreeFormObject}} \ No newline at end of file +{{/isFreeFormObject}} diff --git a/templates/python/search_helpers.mustache b/templates/python/search_helpers.mustache index 13bc0cde4a..f29e0d3226 100644 --- a/templates/python/search_helpers.mustache +++ b/templates/python/search_helpers.mustache @@ -367,4 +367,17 @@ copy_operation_response=copy_operation_response, batch_responses=batch_responses, move_operation_response=move_operation_response, - ) \ No newline at end of file + ) + + 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 \ No newline at end of file diff --git a/templates/python/snippets/method.mustache b/templates/python/snippets/method.mustache index 0b56cc392e..9640deb9b1 100644 --- a/templates/python/snippets/method.mustache +++ b/templates/python/snippets/method.mustache @@ -16,7 +16,7 @@ async def snippet_for_{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}{{test _client = {{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}("YOUR_APP_ID", "YOUR_API_KEY"{{#hasRegionalHost}}, "YOUR_APP_ID_REGION"{{/hasRegionalHost}}) # Call the API - response = await _client.{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}({{#parametersWithDataType}}{{> tests/requests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) + response = await _client.{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}({{#parametersWithDataType}}{{> tests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) # use the class directly print(response) diff --git a/templates/python/tests/client/method.mustache b/templates/python/tests/client/method.mustache index 0e627dd164..13983a8a67 100644 --- a/templates/python/tests/client/method.mustache +++ b/templates/python/tests/client/method.mustache @@ -1 +1 @@ -{{^isError}}_req = {{/isError}}{{#isAsync}}await {{/isAsync}}self._client.{{#lambda.snakecase}}{{{method}}}{{/lambda.snakecase}}{{#useEchoRequester}}_with_http_info{{/useEchoRequester}}({{#parametersWithDataType}}{{> tests/requests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) \ No newline at end of file +{{^isError}}_req = {{/isError}}{{#isAsync}}await {{/isAsync}}self._client.{{#lambda.snakecase}}{{{method}}}{{/lambda.snakecase}}{{#useEchoRequester}}_with_http_info{{/useEchoRequester}}({{#parametersWithDataType}}{{> tests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) \ No newline at end of file diff --git a/templates/python/tests/client/tests.mustache b/templates/python/tests/client/tests.mustache index c2dbbea900..f4c60e4f50 100644 --- a/templates/python/tests/client/tests.mustache +++ b/templates/python/tests/client/tests.mustache @@ -18,32 +18,25 @@ {{^isError}} {{#times}}for _ in range(0, {{.}}): {{/times}}{{#dynamicTemplate}}{{/dynamicTemplate}} - {{#match}} {{#testUserAgent}} - regex_user_agent = compile("{{#lambda.escapeSlash}}{{{match}}}{{/lambda.escapeSlash}}") + regex_user_agent = compile("{{#lambda.escapeSlash}}{{{match.value}}}{{/lambda.escapeSlash}}") assert regex_user_agent.match(_req.headers.get("user-agent")) is not None {{/testUserAgent}} {{#testTimeouts}} - assert _req.timeouts.get("connect") == {{{match.parametersWithDataTypeMap.connectTimeout.value}}} - assert _req.timeouts.get("response") == {{{match.parametersWithDataTypeMap.responseTimeout.value}}} + assert _req.timeouts.get("connect") == {{{matchConnectTimeout}}} + assert _req.timeouts.get("response") == {{{matchResponseTimeout}}} {{/testTimeouts}} {{#testHost}} - assert _req.host == "{{{match}}}" + assert _req.host == "{{{match.value}}}" {{/testHost}} {{#testResponse}} - {{#matchIsJSON}} - assert (_req if isinstance(_req, dict) else [elem.to_dict() for elem in _req] if isinstance(_req, list) else _req.to_dict()) == loads("""{{{match.parameters}}}""") - {{/matchIsJSON}} - {{^matchIsJSON}} - {{#matchIsNull}} - assert _req is None - {{/matchIsNull}} - {{^matchIsNull}} - assert _req == """{{{match}}}""" - {{/matchIsNull}} - {{/matchIsJSON}} + {{^match.isPrimitive}} + assert (_req if isinstance(_req, dict) else [elem.to_dict() for elem in _req] if isinstance(_req, list) else _req.to_dict()) == loads("""{{{match.value}}}""") + {{/match.isPrimitive}} + {{#match.isPrimitive}} + assert _req == {{#match}}{{> tests/generateInnerParams}}{{/match}} + {{/match.isPrimitive}} {{/testResponse}} - {{/match}} {{/isError}} {{/steps}} diff --git a/templates/python/tests/e2e/e2e.mustache b/templates/python/tests/e2e/e2e.mustache index 5100152eb5..b9e948b3cf 100644 --- a/templates/python/tests/e2e/e2e.mustache +++ b/templates/python/tests/e2e/e2e.mustache @@ -28,7 +28,7 @@ class Test{{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}E2E: """ {{{testName}}} """ - raw_resp = await {{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}(self._e2e_app_id, self._e2e_api_key{{#hasRegionalHost}}, "{{{defaultRegion}}}"{{/hasRegionalHost}}).{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}_with_http_info({{#parametersWithDataType}}{{> tests/requests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) + raw_resp = await {{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}(self._e2e_app_id, self._e2e_api_key{{#hasRegionalHost}}, "{{{defaultRegion}}}"{{/hasRegionalHost}}).{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}_with_http_info({{#parametersWithDataType}}{{> tests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) {{#response}} {{#statusCode}} assert raw_resp.status_code == {{statusCode}} @@ -36,7 +36,7 @@ class Test{{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}E2E: {{#body}} - resp = await {{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}(self._e2e_app_id, self._e2e_api_key{{#hasRegionalHost}}, "{{{defaultRegion}}}"{{/hasRegionalHost}}).{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}({{#parametersWithDataType}}{{> tests/requests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) + resp = await {{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}(self._e2e_app_id, self._e2e_api_key{{#hasRegionalHost}}, "{{{defaultRegion}}}"{{/hasRegionalHost}}).{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}({{#parametersWithDataType}}{{> tests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) _expected_body = loads("""{{{.}}}""") assert self._helpers.union(_expected_body, resp) == _expected_body {{/body}} diff --git a/templates/python/tests/generateInnerParams.mustache b/templates/python/tests/generateInnerParams.mustache new file mode 100644 index 0000000000..2a3f34351e --- /dev/null +++ b/templates/python/tests/generateInnerParams.mustache @@ -0,0 +1 @@ +{{#isNull}} None {{/isNull}} {{#isString}} "{{#lambda.escapeSlash}}{{{value}}}{{/lambda.escapeSlash}}" {{/isString}} {{#isInteger}} {{{value}}} {{/isInteger}} {{#isLong}} {{{value}}} {{/isLong}} {{#isDouble}} {{{value}}} {{/isDouble}} {{#isBoolean}} {{#lambda.titlecase}}{{{value}}}{{/lambda.titlecase}} {{/isBoolean}} {{#isEnum}} "{{{value}}}" {{/isEnum}} {{#isArray}} [ {{#value}}{{> tests/generateParams}}{{/value}} ] {{/isArray}} {{#isObject}} { {{#value}}{{> tests/generateParams}}{{/value}} } {{/isObject}} {{#isFreeFormObject}} {{#isAnyType}} { {{#value}}{{#entrySet}}"{{{key}}}":"{{{value}}}"{{^-last}},{{/-last}}{{/entrySet}}{{/value}} } {{/isAnyType}} {{^isAnyType}} { {{#value}}{{> tests/generateParams}}{{/value}} } {{/isAnyType}} {{/isFreeFormObject}} \ No newline at end of file diff --git a/templates/python/tests/generateParams.mustache b/templates/python/tests/generateParams.mustache new file mode 100644 index 0000000000..5af781e858 --- /dev/null +++ b/templates/python/tests/generateParams.mustache @@ -0,0 +1 @@ +{{#isRoot}}{{#lambda.snakecase}}{{{key}}}{{/lambda.snakecase}}={{/isRoot}} {{#useAnonymousKey}}{{#parent}}"{{{key}}}":{{/parent}}{{/useAnonymousKey}} {{> tests/generateInnerParams}}, \ No newline at end of file diff --git a/templates/python/tests/requests/generateParams.mustache b/templates/python/tests/requests/generateParams.mustache deleted file mode 100644 index c204515cf9..0000000000 --- a/templates/python/tests/requests/generateParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isRoot}}{{#lambda.snakecase}}{{{key}}}{{/lambda.snakecase}}={{/isRoot}} {{#useAnonymousKey}}{{#parent}}"{{{key}}}":{{/parent}}{{/useAnonymousKey}} {{#isNull}} None, {{/isNull}} {{#isString}} "{{{value}}}", {{/isString}} {{#isInteger}} {{{value}}}, {{/isInteger}} {{#isLong}} {{{value}}}, {{/isLong}} {{#isDouble}} {{{value}}}, {{/isDouble}} {{#isBoolean}} {{#lambda.titlecase}}{{{value}}}{{/lambda.titlecase}}, {{/isBoolean}} {{#isEnum}} "{{{value}}}", {{/isEnum}} {{#isArray}} [ {{#value}}{{> tests/requests/generateParams}}{{/value}} ], {{/isArray}} {{#isObject}} { {{#value}}{{> tests/requests/generateParams}}{{/value}} }, {{/isObject}} {{#isFreeFormObject}} {{#isAnyType}} { {{#value}}{{#entrySet}}"{{{key}}}":"{{{value}}}"{{^-last}},{{/-last}}{{/entrySet}}{{/value}} }, {{/isAnyType}} {{^isAnyType}} { {{#value}}{{> tests/requests/generateParams}}{{/value}} }, {{/isAnyType}} {{/isFreeFormObject}} \ No newline at end of file diff --git a/templates/python/tests/requests/requests.mustache b/templates/python/tests/requests/requests.mustache index 8a227d65fb..4ecca4e59e 100644 --- a/templates/python/tests/requests/requests.mustache +++ b/templates/python/tests/requests/requests.mustache @@ -19,7 +19,7 @@ class Test{{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}: """ {{{testName}}} """ - _req = await self._client.{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}_with_http_info({{#parametersWithDataType}}{{> tests/requests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) + _req = await self._client.{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}_with_http_info({{#parametersWithDataType}}{{> tests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}} request_options={ {{#requestOptions.headers.parameters}}"headers":loads("""{{{.}}}"""),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}"query_parameters":loads("""{{{.}}}"""),{{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) {{#request}} assert _req.path == "{{{path}}}" diff --git a/templates/ruby/search_helpers.mustache b/templates/ruby/search_helpers.mustache index e77843dfea..d333beb79f 100644 --- a/templates/ruby/search_helpers.mustache +++ b/templates/ruby/search_helpers.mustache @@ -361,4 +361,16 @@ def replace_all_objects(index_name, objects, batch_size = 1000, request_options batch_responses: batch_responses, 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 \ No newline at end of file diff --git a/templates/ruby/tests/client/method.mustache b/templates/ruby/tests/client/method.mustache index bc1207fb1c..93128e5fb8 100644 --- a/templates/ruby/tests/client/method.mustache +++ b/templates/ruby/tests/client/method.mustache @@ -1 +1 @@ -{{^isError}}req = {{/isError}}client.{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}{{#useEchoRequester}}_with_http_info{{/useEchoRequester}}({{#parametersWithDataType}}{{> tests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}}{ {{#requestOptions.headers.parameters}}:header_params => JSON.parse('{{{.}}}', :symbolize_names => true),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}:query_params => JSON.parse('{{{.}}}', :symbolize_names => true){{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) \ No newline at end of file +{{^isError}}req = {{/isError}}client.{{#lambda.snakecase}}{{method}}{{/lambda.snakecase}}{{#useEchoRequester}}_with_http_info{{/useEchoRequester}}{{#returnsBoolean}}?{{/returnsBoolean}}({{#parametersWithDataType}}{{> tests/generateParams}}{{/parametersWithDataType}}{{#hasRequestOptions}}{ {{#requestOptions.headers.parameters}}:header_params => JSON.parse('{{{.}}}', :symbolize_names => true),{{/requestOptions.headers.parameters}}{{#requestOptions.queryParameters.parameters}}:query_params => JSON.parse('{{{.}}}', :symbolize_names => true){{/requestOptions.queryParameters.parameters}} }{{/hasRequestOptions}}) \ No newline at end of file diff --git a/templates/ruby/tests/client/tests.mustache b/templates/ruby/tests/client/tests.mustache index 6e79daeda6..3b93e38fb0 100644 --- a/templates/ruby/tests/client/tests.mustache +++ b/templates/ruby/tests/client/tests.mustache @@ -23,31 +23,24 @@ {{/isError}} {{^isError}} {{#dynamicTemplate}}{{/dynamicTemplate}} - {{#match}} {{#testUserAgent}} - assert(req.headers['user-agent'].match(/{{{match}}}/)) + assert(req.headers['user-agent'].match(/{{{match.value}}}/)) {{/testUserAgent}} {{#testTimeouts}} - assert_equal({{{match.parametersWithDataTypeMap.connectTimeout.value}}}, req.connect_timeout) - assert_equal({{{match.parametersWithDataTypeMap.responseTimeout.value}}}, req.timeout) + assert_equal({{{matchConnectTimeout}}}, req.connect_timeout) + assert_equal({{{matchResponseTimeout}}}, req.timeout) {{/testTimeouts}} {{#testHost}} - assert_equal('{{{match}}}', req.host.url) + assert_equal('{{{match.value}}}', req.host.url) {{/testHost}} {{#testResponse}} - {{#matchIsJSON}} - assert_equal({{{match.parameters}}}, req.is_a?(Array) ? req.map(&:to_hash) : req.to_hash) - {{/matchIsJSON}} - {{^matchIsJSON}} - {{#matchIsNull}} - assert_nil(req) - {{/matchIsNull}} - {{^matchIsNull}} - assert_equal('{{{match}}}', req) - {{/matchIsNull}} - {{/matchIsJSON}} + {{^match.isPrimitive}} + assert_equal({{{match.value}}}, req.is_a?(Array) ? req.map(&:to_hash) : req.to_hash) + {{/match.isPrimitive}} + {{#match.isPrimitive}} + assert_equal({{#match}}{{> tests/generateInnerParams}}{{/match}}, req) + {{/match.isPrimitive}} {{/testResponse}} - {{/match}} {{/isError}} {{#times}} end diff --git a/templates/ruby/tests/generateInnerParams.mustache b/templates/ruby/tests/generateInnerParams.mustache new file mode 100644 index 0000000000..8f1c843bdc --- /dev/null +++ b/templates/ruby/tests/generateInnerParams.mustache @@ -0,0 +1 @@ +{{#isNull}}nil {{/isNull}}{{#isString}}"{{{value}}}" {{/isString}}{{#isInteger}}{{{value}}} {{/isInteger}}{{#isLong}}{{{value}}} {{/isLong}}{{#isDouble}}{{{value}}} {{/isDouble}}{{#isBoolean}}{{{value}}} {{/isBoolean}} {{#isEnum}}'{{{value}}}' {{/isEnum}}{{#isArray}} [ {{#value}}{{> tests/generateParams}}{{/value}} ] {{/isArray}}{{#isObject}} {{{objectName}}}.new({{#value}}{{> tests/generateParams}}{{/value}}) {{/isObject}}{{#isFreeFormObject}} {{#isAnyType}} { {{#value}}{{#entrySet}}'{{{key}}}':"{{{value}}}"{{^-last}},{{/-last}}{{/entrySet}}{{/value}} } {{/isAnyType}} {{^isAnyType}} { {{#value}}{{> tests/generateParams}}{{/value}} } {{/isAnyType}} {{/isFreeFormObject}} \ No newline at end of file diff --git a/templates/ruby/tests/generateParams.mustache b/templates/ruby/tests/generateParams.mustache index 091edc8bb0..55cdf91786 100644 --- a/templates/ruby/tests/generateParams.mustache +++ b/templates/ruby/tests/generateParams.mustache @@ -1 +1 @@ -{{#useAnonymousKey}}{{#lambda.escapeRubyKeywords}}{{{key}}}{{/lambda.escapeRubyKeywords}}: {{/useAnonymousKey}}{{#isNull}}nil, {{/isNull}}{{#isString}}"{{{value}}}", {{/isString}}{{#isInteger}}{{{value}}}, {{/isInteger}}{{#isLong}}{{{value}}}, {{/isLong}}{{#isDouble}}{{{value}}}, {{/isDouble}}{{#isBoolean}}{{{value}}}, {{/isBoolean}} {{#isEnum}}'{{{value}}}', {{/isEnum}}{{#isArray}} [ {{#value}}{{> tests/generateParams}}{{/value}} ], {{/isArray}}{{#isObject}} {{{objectName}}}.new({{#value}}{{> tests/generateParams}}{{/value}}), {{/isObject}}{{#isFreeFormObject}} {{#isAnyType}} { {{#value}}{{#entrySet}}'{{{key}}}':"{{{value}}}"{{^-last}},{{/-last}}{{/entrySet}}{{/value}} }, {{/isAnyType}} {{^isAnyType}} { {{#value}}{{> tests/generateParams}}{{/value}} }, {{/isAnyType}} {{/isFreeFormObject}} \ No newline at end of file +{{#useAnonymousKey}}{{#lambda.escapeRubyKeywords}}{{{key}}}{{/lambda.escapeRubyKeywords}}: {{/useAnonymousKey}}{{> tests/generateInnerParams}}, \ No newline at end of file diff --git a/templates/scala/tests/client/client.mustache b/templates/scala/tests/client/client.mustache index 5a52986840..8394c489a8 100644 --- a/templates/scala/tests/client/client.mustache +++ b/templates/scala/tests/client/client.mustache @@ -55,33 +55,26 @@ class {{clientPrefix}}Test extends AnyFunSuite { {{/isError}} {{^isError}} {{#dynamicTemplate}}{{/dynamicTemplate}} - {{#match}} {{#testUserAgent}} - val regexp = """{{{match}}}""".r + val regexp = """{{{match.value}}}""".r val header = echo.lastResponse.get.headers("user-agent") assert(header.matches(regexp.regex), s"Expected $header to match the following regex: ${regexp.regex}") {{/testUserAgent}} {{#testTimeouts}} - assert(echo.lastResponse.get.connectTimeout == {{{match.parametersWithDataTypeMap.connectTimeout.value}}}) - assert(echo.lastResponse.get.responseTimeout == {{{match.parametersWithDataTypeMap.responseTimeout.value}}}) + assert(echo.lastResponse.get.connectTimeout == {{{matchConnectTimeout}}}) + assert(echo.lastResponse.get.responseTimeout == {{{matchResponseTimeout}}}) {{/testTimeouts}} {{#testHost}} - assert(echo.lastResponse.get.host == "{{{match}}}") + assert(echo.lastResponse.get.host == "{{{match.value}}}") {{/testHost}} {{#testResponse}} - {{#matchIsJSON}} - assert(write(res) == "{{#lambda.escapeQuotes}}{{{match.parameters}}}{{/lambda.escapeQuotes}}") - {{/matchIsJSON}} - {{^matchIsJSON}} - {{#matchIsNull}} - assert(res == null) - {{/matchIsNull}} - {{^matchIsNull}} - assert(res == "{{{match}}}") - {{/matchIsNull}} - {{/matchIsJSON}} + {{^match.isPrimitive}} + assert(write(res) == "{{#lambda.escapeQuotes}}{{{match.value}}}{{/lambda.escapeQuotes}}") + {{/match.isPrimitive}} + {{#match.isPrimitive}} + assert(res == {{#match}}{{> tests/param_value}}{{/match}}) + {{/match.isPrimitive}} {{/testResponse}} - {{/match}} {{/isError}} {{/steps}} } diff --git a/templates/swift/tests/client/tests.mustache b/templates/swift/tests/client/tests.mustache index 73ffef9fb1..e7ea6e855f 100644 --- a/templates/swift/tests/client/tests.mustache +++ b/templates/swift/tests/client/tests.mustache @@ -25,49 +25,45 @@ {{/isError}} {{^isError}} {{#dynamicTemplate}}{{/dynamicTemplate}} - {{#match}} - {{#testUserAgent}} + {{#testUserAgent}} - let pattern = "{{#lambda.escapeSlash}}{{{match}}}{{/lambda.escapeSlash}}" - let rule = StringRule(pattern: pattern) - let userAgent = try XCTUnwrap(echoResponse.headers?["User-Agent"]) - guard let userAgent = userAgent else { - XCTFail("Expected user-agent header") - return - } + let pattern = "{{#lambda.escapeSlash}}{{{match.value}}}{{/lambda.escapeSlash}}" + let rule = StringRule(pattern: pattern) + let userAgent = try XCTUnwrap(echoResponse.headers?["User-Agent"]) + guard let userAgent = userAgent else { + XCTFail("Expected user-agent header") + return + } - XCTAssertNoThrow(try Validator.validate(userAgent, against: rule), "Expected " + userAgent + " to match the following regex: " + pattern); - {{/testUserAgent}} - - {{#testTimeouts}} - - XCTAssertEqual(TimeInterval({{{match.parametersWithDataTypeMap.responseTimeout.value}}} / 1000), echoResponse.timeout); - {{/testTimeouts}} - {{#testHost}} - XCTAssertEqual("{{{match}}}", echoResponse.host); - {{/testHost}} - {{#testResponse}} - {{#isHelper}} - {{#matchIsJSON}} - let comparableData = try XCTUnwrap("{{#lambda.escapeQuotes}}{{{match.parameters}}}{{/lambda.escapeQuotes}}".data(using: .utf8)) - try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) - {{/matchIsJSON}} - {{^matchIsJSON}} - {{#matchIsNull}} - XCTAssertNil(response) - {{/matchIsNull}} - {{^matchIsNull}} - XCTAssertEqual("{{#lambda.escapeQuotes}}{{{match}}}{{/lambda.escapeQuotes}}", response) - {{/matchIsNull}} - {{/matchIsJSON}} - {{/isHelper}} - {{^isHelper}} - let comparableData = "{{#lambda.escapeQuotes}}{{#matchIsJSON}}{{{match.parameters}}}{{/matchIsJSON}}{{^matchIsJSON}}{{{match}}}{{/matchIsJSON}}{{/lambda.escapeQuotes}}".data(using: .utf8) - let comparableJSON = try XCTUnwrap(comparableData?.jsonString) - XCTAssertEqual(comparableJSON, responseBodyJSON); - {{/isHelper}} - {{/testResponse}} - {{/match}} + XCTAssertNoThrow(try Validator.validate(userAgent, against: rule), "Expected " + userAgent + " to match the following regex: " + pattern); + {{/testUserAgent}} + {{#testTimeouts}} + XCTAssertEqual(TimeInterval({{{matchResponseTimeout}}} / 1000), echoResponse.timeout); + {{/testTimeouts}} + {{#testHost}} + XCTAssertEqual("{{{match.value}}}", echoResponse.host); + {{/testHost}} + {{#testResponse}} + {{#isHelper}} + {{^match.isPrimitive}} + let comparableData = try XCTUnwrap("{{#lambda.escapeQuotes}}{{{match.value}}}{{/lambda.escapeQuotes}}".data(using: .utf8)) + try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) + {{/match.isPrimitive}} + {{#match.isPrimitive}} + {{#match.isNull}} + XCTAssertNil(response) + {{/match.isNull}} + {{^match.isNull}} + XCTAssertEqual({{#match}}{{> tests/paramValue}}{{/match}}, response) + {{/match.isNull}} + {{/match.isPrimitive}} + {{/isHelper}} + {{^isHelper}} + let comparableData = "{{#lambda.escapeQuotes}}{{{match.value}}}{{/lambda.escapeQuotes}}".data(using: .utf8) + let comparableJSON = try XCTUnwrap(comparableData?.jsonString) + XCTAssertEqual(comparableJSON, responseBodyJSON); + {{/isHelper}} + {{/testResponse}} {{/isError}} {{#times}} } diff --git a/tests/CTS/client/search/indexExists.json b/tests/CTS/client/search/indexExists.json new file mode 100644 index 0000000000..f42c7f8963 --- /dev/null +++ b/tests/CTS/client/search/indexExists.json @@ -0,0 +1,101 @@ +[ + { + "testName": "indexExists", + "autoCreateClient": false, + "steps": [ + { + "type": "createClient", + "parameters": { + "appId": "test-app-id", + "apiKey": "test-api-key", + "customHosts": [ + { + "host": "${{localhost}}", + "port": 6681 + } + ] + } + }, + { + "type": "method", + "method": "indexExists", + "parameters": { + "indexName": "indexExistsYES" + }, + "expected": { + "type": "response", + "match": true + } + } + ] + }, + { + "testName": "indexNotExists", + "autoCreateClient": false, + "steps": [ + { + "type": "createClient", + "parameters": { + "appId": "test-app-id", + "apiKey": "test-api-key", + "customHosts": [ + { + "host": "${{localhost}}", + "port": 6681 + } + ] + } + }, + { + "type": "method", + "method": "indexExists", + "parameters": { + "indexName": "indexExistsNO" + }, + "expected": { + "type": "response", + "match": false + } + } + ] + }, + { + "testName": "indexExistsWithError", + "autoCreateClient": false, + "steps": [ + { + "type": "createClient", + "parameters": { + "appId": "test-app-id", + "apiKey": "test-api-key", + "customHosts": [ + { + "host": "${{localhost}}", + "port": 6681 + } + ] + } + }, + { + "type": "method", + "method": "indexExists", + "parameters": { + "indexName": "indexExistsERROR" + }, + "expected": { + "error": { + "csharp": "{\\\"message\\\":\\\"Invalid API key\\\"}", + "go": "API error [403] {\\\"message\\\":\\\"Invalid API key\\\"}", + "java": "Status Code: 403 - {\\\"message\\\":\\\"Invalid API key\\\"}", + "javascript": "Invalid API key", + "kotlin": "Client request(GET http://${{localhost}}:6681/1/indexes/indexExistsERROR/settings) invalid: 403 Forbidden. Text: \\\"{\\\"message\\\":\\\"Invalid API key\\\"}\\\"", + "php": "Invalid API key", + "python": "Invalid API key", + "ruby": "Invalid API key", + "swift": "HTTP error: Status code: 403 Message: Invalid API key" + } + } + } + ] + } +] diff --git a/tests/output/javascript/yarn.lock b/tests/output/javascript/yarn.lock index 810c59c0b7..53d6cc473b 100644 --- a/tests/output/javascript/yarn.lock +++ b/tests/output/javascript/yarn.lock @@ -923,7 +923,7 @@ __metadata: languageName: node linkType: hard -"@types/node@npm:*, @types/node@npm:22.5.0": +"@types/node@npm:*": version: 22.5.0 resolution: "@types/node@npm:22.5.0" dependencies: @@ -932,6 +932,15 @@ __metadata: languageName: node linkType: hard +"@types/node@npm:22.5.1": + version: 22.5.1 + resolution: "@types/node@npm:22.5.1" + dependencies: + undici-types: "npm:~6.19.2" + checksum: 10/adcec0e8a9ec9112a8cc9529b7d633356c2377fe69ca6e6de4ee39cacb8c86a18a9b7ba658e2456f8ad90d5b76767b268f517b0336c6db787cb056dcdfed107a + languageName: node + linkType: hard + "@types/stack-utils@npm:^2.0.0": version: 2.0.3 resolution: "@types/stack-utils@npm:2.0.3" @@ -2056,7 +2065,7 @@ __metadata: "@algolia/recommend": "link:../../../clients/algoliasearch-client-javascript/packages/recommend" "@algolia/requester-node-http": "link:../../../clients/algoliasearch-client-javascript/packages/requester-node-http" "@types/jest": "npm:29.5.12" - "@types/node": "npm:22.5.0" + "@types/node": "npm:22.5.1" algoliasearch: "link:../../../clients/algoliasearch-client-javascript/packages/algoliasearch" dotenv: "npm:16.4.5" jest: "npm:29.7.0" diff --git a/tests/output/python/pyproject.toml b/tests/output/python/pyproject.toml index 28ee732544..4760355589 100644 --- a/tests/output/python/pyproject.toml +++ b/tests/output/python/pyproject.toml @@ -18,3 +18,6 @@ pytest-aiohttp = "1.0.5" [tool.pytest.ini_options] asyncio_mode = "auto" testpaths = ["tests"] + +[tool.ruff] +unsafe-fixes = true \ No newline at end of file