From 4b4d3162a42d895c56901c7ad712ea109333b7d1 Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Wed, 1 Jun 2022 18:44:45 +0200 Subject: [PATCH 1/7] fix(cts): move the client test from ts to java --- config/openapitools.json | 67 ++----- .../algolia/codegen/AlgoliaJavaGenerator.java | 2 +- .../codegen/AlgoliaJavaScriptGenerator.java | 2 +- .../algolia/codegen/AlgoliaPhpGenerator.java | 2 +- .../main/java/com/algolia/codegen/Utils.java | 32 ++-- .../codegen/cts/AlgoliaCTSGenerator.java | 1 + .../codegen/cts/manager/JavaCTSManager.java | 2 +- .../codegen/cts/tests/ClientTestData.java | 33 ++++ .../cts/tests/ParametersWithDataType.java | 90 ++++++---- .../codegen/cts/tests/TestsClient.java | 106 ++++++++++- .../codegen/cts/tests/TestsRequest.java | 6 +- scripts/__tests__/common.test.ts | 41 ++++- scripts/common.ts | 28 +++ scripts/cts/client/generate.ts | 165 ------------------ scripts/cts/client/types.ts | 54 ------ scripts/cts/generate.ts | 11 +- scripts/cts/integrations/.gitkeep | 0 scripts/cts/utils.test.ts | 40 ----- scripts/cts/utils.ts | 115 ------------ scripts/playground.ts | 8 +- scripts/pre-gen/removeExistingCodegen.ts | 3 +- .../tests/client/createClient.mustache | 4 +- .../javascript/tests/client/expected.mustache | 13 -- .../javascript/tests/client/step.mustache | 10 +- .../javascript/tests/client/suite.mustache | 71 +++----- .../tests/client/testSubject.mustache | 9 +- tests/CTS/client/abtesting/api.json | 46 +++-- tests/CTS/client/abtesting/parameters.json | 12 +- tests/CTS/client/analytics/api.json | 18 +- tests/CTS/client/analytics/parameters.json | 16 +- tests/CTS/client/insights/api.json | 18 +- tests/CTS/client/insights/parameters.json | 12 +- tests/CTS/client/personalization/api.json | 6 +- .../client/personalization/parameters.json | 4 +- tests/CTS/client/predict/api.json | 34 ++-- tests/CTS/client/predict/parameters.json | 4 +- tests/CTS/client/query-suggestions/api.json | 10 +- .../client/query-suggestions/parameters.json | 4 +- tests/CTS/client/recommend/api.json | 26 ++- tests/CTS/client/search/api.json | 50 +++--- tests/CTS/client/search/parameters.json | 34 ++-- tests/CTS/client/sources/api.json | 68 ++++---- tests/CTS/client/sources/parameters.json | 4 +- 43 files changed, 488 insertions(+), 793 deletions(-) create mode 100644 generators/src/main/java/com/algolia/codegen/cts/tests/ClientTestData.java delete mode 100644 scripts/cts/client/generate.ts delete mode 100644 scripts/cts/client/types.ts delete mode 100644 scripts/cts/integrations/.gitkeep delete mode 100644 scripts/cts/utils.test.ts delete mode 100644 scripts/cts/utils.ts delete mode 100644 templates/javascript/tests/client/expected.mustache diff --git a/config/openapitools.json b/config/openapitools.json index 034f14ca008..0b36f0b23b0 100644 --- a/config/openapitools.json +++ b/config/openapitools.json @@ -34,8 +34,7 @@ "additionalProperties": { "packageName": "@experimental-api-clients-automation/client-personalization", "buildFile": "client-personalization", - "packageVersion": "0.3.0", - "hasRegionalHost": true + "packageVersion": "0.3.0" } }, "javascript-analytics": { @@ -43,8 +42,7 @@ "additionalProperties": { "packageName": "@experimental-api-clients-automation/client-analytics", "buildFile": "client-analytics", - "packageVersion": "0.3.0", - "hasRegionalHost": true + "packageVersion": "0.3.0" } }, "javascript-insights": { @@ -52,8 +50,7 @@ "additionalProperties": { "packageName": "@experimental-api-clients-automation/client-insights", "buildFile": "client-insights", - "packageVersion": "0.3.0", - "hasRegionalHost": true + "packageVersion": "0.3.0" } }, "javascript-abtesting": { @@ -61,8 +58,7 @@ "additionalProperties": { "packageName": "@experimental-api-clients-automation/client-abtesting", "buildFile": "client-abtesting", - "packageVersion": "0.3.0", - "hasRegionalHost": true + "packageVersion": "0.3.0" } }, "javascript-query-suggestions": { @@ -70,8 +66,7 @@ "additionalProperties": { "packageName": "@experimental-api-clients-automation/client-query-suggestions", "buildFile": "client-query-suggestions", - "packageVersion": "0.3.0", - "hasRegionalHost": true + "packageVersion": "0.3.0" } }, "javascript-sources": { @@ -79,18 +74,15 @@ "additionalProperties": { "packageName": "@experimental-api-clients-automation/client-sources", "buildFile": "client-sources", - "packageVersion": "0.3.0", - "hasRegionalHost": true + "packageVersion": "0.3.0" } }, "javascript-predict": { - "templateDir": "#{cwd}/templates/javascript/", "output": "#{cwd}/clients/algoliasearch-client-javascript/packages/client-predict", "additionalProperties": { "packageName": "@experimental-api-clients-automation/client-predict", "buildFile": "client-predict", - "packageVersion": "0.3.0", - "hasRegionalHost": true + "packageVersion": "0.3.0" } }, "java-search": { @@ -100,34 +92,19 @@ "output": "#{cwd}/clients/algoliasearch-client-java-2" }, "java-personalization": { - "output": "#{cwd}/clients/algoliasearch-client-java-2", - "additionalProperties": { - "hasRegionalHost": true - } + "output": "#{cwd}/clients/algoliasearch-client-java-2" }, "java-analytics": { - "output": "#{cwd}/clients/algoliasearch-client-java-2", - "additionalProperties": { - "hasRegionalHost": true - } + "output": "#{cwd}/clients/algoliasearch-client-java-2" }, "java-insights": { - "output": "#{cwd}/clients/algoliasearch-client-java-2", - "additionalProperties": { - "hasRegionalHost": true - } + "output": "#{cwd}/clients/algoliasearch-client-java-2" }, "java-abtesting": { - "output": "#{cwd}/clients/algoliasearch-client-java-2", - "additionalProperties": { - "hasRegionalHost": true - } + "output": "#{cwd}/clients/algoliasearch-client-java-2" }, "java-query-suggestions": { - "output": "#{cwd}/clients/algoliasearch-client-java-2", - "additionalProperties": { - "hasRegionalHost": true - } + "output": "#{cwd}/clients/algoliasearch-client-java-2" }, "java-predict": { "output": "#{cwd}/clients/algoliasearch-client-java-2" @@ -139,28 +116,16 @@ "output": "#{cwd}/clients/algoliasearch-client-php" }, "php-personalization": { - "output": "#{cwd}/clients/algoliasearch-client-php", - "additionalProperties": { - "hasRegionalHost": true - } + "output": "#{cwd}/clients/algoliasearch-client-php" }, "php-analytics": { - "output": "#{cwd}/clients/algoliasearch-client-php", - "additionalProperties": { - "hasRegionalHost": true - } + "output": "#{cwd}/clients/algoliasearch-client-php" }, "php-insights": { - "output": "#{cwd}/clients/algoliasearch-client-php", - "additionalProperties": { - "hasRegionalHost": true - } + "output": "#{cwd}/clients/algoliasearch-client-php" }, "php-abtesting": { - "output": "#{cwd}/clients/algoliasearch-client-php", - "additionalProperties": { - "hasRegionalHost": true - } + "output": "#{cwd}/clients/algoliasearch-client-php" }, "php-query-suggestions": { "output": "#{cwd}/clients/algoliasearch-client-php" diff --git a/generators/src/main/java/com/algolia/codegen/AlgoliaJavaGenerator.java b/generators/src/main/java/com/algolia/codegen/AlgoliaJavaGenerator.java index 9ba10dd30f5..9c8ea8a1625 100644 --- a/generators/src/main/java/com/algolia/codegen/AlgoliaJavaGenerator.java +++ b/generators/src/main/java/com/algolia/codegen/AlgoliaJavaGenerator.java @@ -25,7 +25,7 @@ public void processOpts() { setLibrary("okhttp-gson"); setSourceFolder("algoliasearch-core/src/main/java"); setGroupId("com.algolia"); - setModelPackage("com.algolia.model." + Utils.toCamelCase(client)); + setModelPackage("com.algolia.model." + Utils.camelize(client)); additionalProperties.put("invokerPackage", "com.algolia"); setApiPackage("com.algolia.api"); setApiNameSuffix(Utils.API_SUFFIX); diff --git a/generators/src/main/java/com/algolia/codegen/AlgoliaJavaScriptGenerator.java b/generators/src/main/java/com/algolia/codegen/AlgoliaJavaScriptGenerator.java index 34286d2452f..10f4364b091 100644 --- a/generators/src/main/java/com/algolia/codegen/AlgoliaJavaScriptGenerator.java +++ b/generators/src/main/java/com/algolia/codegen/AlgoliaJavaScriptGenerator.java @@ -24,7 +24,7 @@ public String getName() { public void processOpts() { super.processOpts(); - CLIENT = Utils.toCamelCase((String) additionalProperties.get("client")); + CLIENT = Utils.camelize((String) additionalProperties.get("client")); // generator specific options setSupportsES6(true); diff --git a/generators/src/main/java/com/algolia/codegen/AlgoliaPhpGenerator.java b/generators/src/main/java/com/algolia/codegen/AlgoliaPhpGenerator.java index 92d9f0a93a1..98d7511bbf6 100644 --- a/generators/src/main/java/com/algolia/codegen/AlgoliaPhpGenerator.java +++ b/generators/src/main/java/com/algolia/codegen/AlgoliaPhpGenerator.java @@ -22,7 +22,7 @@ public void processOpts() { String client = (String) additionalProperties.get("client"); setApiNameSuffix(Utils.API_SUFFIX); setParameterNamingConvention("camelCase"); - additionalProperties.put("modelPackage", "Model\\" + Utils.toPascalCase(client)); + additionalProperties.put("modelPackage", "Model\\" + Utils.createClientName(client, "php")); additionalProperties.put("invokerPackage", "Algolia\\AlgoliaSearch"); super.processOpts(); diff --git a/generators/src/main/java/com/algolia/codegen/Utils.java b/generators/src/main/java/com/algolia/codegen/Utils.java index c79dafe18c3..299f2cf2df6 100644 --- a/generators/src/main/java/com/algolia/codegen/Utils.java +++ b/generators/src/main/java/com/algolia/codegen/Utils.java @@ -27,6 +27,15 @@ public static String capitalize(String str) { return str.substring(0, 1).toUpperCase() + str.substring(1); } + public static String camelize(String kebabStr) { + String[] parts = kebabStr.split("-"); + String camel = parts[0].toLowerCase(); + for (int i = 1; i < parts.length; i++) { + camel += capitalize(parts[i]); + } + return camel; + } + /** * Will add the boolean `vendorExtensions.x-is-custom-request` to operations if they should not * escape '/' in the path variable @@ -40,28 +49,7 @@ public static CodegenOperation specifyCustomRequest(CodegenOperation ope) { /** Returns the client name for the given language */ public static String createClientName(String client, String language) { - return language.equals("javascript") ? toCamelCase(client) : toPascalCase(client); - } - - // test-input -> testInput - public static String toCamelCase(String kebabStr) { - String[] parts = kebabStr.split("-"); - String camel = ""; - camel = parts[0].toLowerCase(); - for (int i = 1; i < parts.length; i++) { - camel += capitalize(parts[i]); - } - return camel; - } - - // test-input -> TestInput - public static String toPascalCase(String kebabStr) { - String[] parts = kebabStr.split("-"); - String pascal = ""; - for (int i = 0; i < parts.length; i++) { - pascal += capitalize(parts[i]); - } - return pascal; + return language.equals("javascript") ? camelize(client) : capitalize(camelize(client)); } // testInput -> test-input diff --git a/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java b/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java index 3b8b70901ec..d77d8b6f5ef 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java +++ b/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java @@ -48,6 +48,7 @@ public void processOpts() { ctsManager.addSupportingFiles(supportingFiles); testsGenerators.add(new TestsRequest(language, client)); + testsGenerators.add(new TestsClient(language, client)); for (TestsGenerator testGen : testsGenerators) { testGen.addSupportingFiles(supportingFiles, outputFolder, extension); diff --git a/generators/src/main/java/com/algolia/codegen/cts/manager/JavaCTSManager.java b/generators/src/main/java/com/algolia/codegen/cts/manager/JavaCTSManager.java index 36543be5952..48673ace4a2 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/manager/JavaCTSManager.java +++ b/generators/src/main/java/com/algolia/codegen/cts/manager/JavaCTSManager.java @@ -21,6 +21,6 @@ public void addSupportingFiles(List supportingFiles) { @Override public void addDataToBundle(Map bundle) throws GeneratorException { bundle.put("packageVersion", Utils.getClientConfigField("java", "packageVersion")); - bundle.put("import", Utils.toCamelCase(this.client)); + bundle.put("import", Utils.camelize(this.client)); } } diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/ClientTestData.java b/generators/src/main/java/com/algolia/codegen/cts/tests/ClientTestData.java new file mode 100644 index 00000000000..4ec916d07ff --- /dev/null +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/ClientTestData.java @@ -0,0 +1,33 @@ +package com.algolia.codegen.cts.tests; + +import java.util.List; +import java.util.Map; + +public class ClientTestData { + + public String testName; + public boolean autoCreateClient = true; + public List steps; +} + +class Step { + + public String type; + public String object; + public String path; + public Map parameters; + public Expected expected; +} + +class Expected { + + public Object error; + public Match match; + public String testSubject = "result"; +} + +class Match { + + public String regexp; + public Map objectContaining; +} 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 2667ab9d03c..3506364a801 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 @@ -28,49 +28,77 @@ public ParametersWithDataType(Map models, String language) public void enhanceParameters(Map parameters, Map bundle, CodegenOperation operation) throws CTSException, JsonMappingException, JsonProcessingException { - if (parameters == null || parameters.size() == 0) { - return; - } - // Give the stringified version to mustache, for js - bundle.put("parameters", Json.mapper().writeValueAsString(parameters)); - - List parametersWithDataType = new ArrayList<>(); + this.enhanceParameters(parameters, bundle, operation, null, null); + } - for (Entry param : parameters.entrySet()) { - CodegenParameter specParam = null; - if (operation != null) { - for (CodegenParameter sp : operation.allParams) { - if (sp.paramName.equals(param.getKey())) { - specParam = sp; - break; - } - } - if (specParam == null) { - throw new CTSException("Parameter " + param.getKey() + " not found in the root parameter"); - } - } - parametersWithDataType.add(traverseParams(param.getKey(), param.getValue(), specParam, "", 0)); - } + public void enhanceParameters( + Map parameters, + Map bundle, + IJsonSchemaValidationProperties spec, + String paramName + ) throws CTSException, JsonMappingException, JsonProcessingException { + this.enhanceParameters(parameters, bundle, null, spec, paramName); + } - bundle.put("parametersWithDataType", parametersWithDataType); + public void enhanceParameters(Map parameters, Map bundle) + throws CTSException, JsonMappingException, JsonProcessingException { + this.enhanceParameters(parameters, bundle, null, null, null); } - public void enhanceRootParameters( + /** + * @param parameters The object to traverse and annotate with type + * @param bundle The output object + * @param operation (optional) The model in which to look for spec + * @param spec (optional) (mutually exclusive with operation) If the parameter is a root param, + * the spec must be provided, alongside it's paramName + * @param paramName (optional) (required if spec) the parameter name + */ + private void enhanceParameters( Map parameters, - String paramName, + Map bundle, + CodegenOperation operation, IJsonSchemaValidationProperties spec, - Map bundle + String paramName ) throws CTSException, JsonMappingException, JsonProcessingException { - if (parameters == null || parameters.size() == 0) { + if (parameters == null) { + return; + } + if (parameters.size() == 0) { + bundle.put("parameters", "{}"); return; } + List> parametersWithDataType = new ArrayList<>(); + Map parametersWithDataTypeMap = new HashMap<>(); + + if (paramName == null) { + for (Entry param : parameters.entrySet()) { + CodegenParameter specParam = null; + if (operation != null) { + for (CodegenParameter sp : operation.allParams) { + if (sp.paramName.equals(param.getKey())) { + specParam = sp; + break; + } + } + if (specParam == null) { + throw new CTSException("Parameter " + param.getKey() + " not found in the root parameter"); + } + } + Map paramWithType = traverseParams(param.getKey(), param.getValue(), specParam, "", 0); + parametersWithDataType.add(paramWithType); + parametersWithDataTypeMap.put((String) paramWithType.get("key"), paramWithType); + } + } else { + Map paramWithType = traverseParams(paramName, parameters, spec, "", 0); + parametersWithDataType.add(paramWithType); + parametersWithDataTypeMap.put((String) paramWithType.get("key"), paramWithType); + } + // Give the stringified version to mustache, for js bundle.put("parameters", Json.mapper().writeValueAsString(parameters)); - - List parametersWithDataType = new ArrayList<>(); - parametersWithDataType.add(traverseParams(paramName, parameters, spec, "", 0)); - bundle.put("parametersWithDataType", parametersWithDataType); + // Also provide a map version for those who know which keys to look for + bundle.put("parametersWithDataTypeMap", parametersWithDataTypeMap); } private Map traverseParams( 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 e9c5e50fe8d..b056593f42f 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 @@ -1,6 +1,108 @@ package com.algolia.codegen.cts.tests; -public class TestsClient { +import com.algolia.codegen.Utils; +import com.algolia.codegen.exceptions.CTSException; +import io.swagger.v3.core.util.Json; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.SupportingFile; - public static void run() {} +public class TestsClient implements TestsGenerator { + + private final String language, client; + + public TestsClient(String language, String client) { + this.language = language; + this.client = client; + } + + private Map loadCTS() throws Exception { + Map cts = new HashMap<>(); + String clientName = client; + // This special case allow us to read the `search` CTS to generated the tests for the + // `algoliasearch-lite` client, which is only available in JavaScript + if (language.equals("javascript") && client.equals("algoliasearch-lite")) { + throw new CTSException("Don't generate test for algoliasearch-lite for now", true); + } + + File dir = new File("tests/CTS/client/" + clientName); + if (!dir.exists()) { + throw new CTSException("CTS not found at " + dir.getAbsolutePath(), true); + } + for (File f : dir.listFiles()) { + cts.put(f.getName().replace(".json", ""), Json.mapper().readValue(f, ClientTestData[].class)); + } + return cts; + } + + @Override + public void addSupportingFiles(List supportingFiles, String outputFolder, String extension) { + String clientName = language.equals("php") ? Utils.createClientName(client, language) : client; + supportingFiles.add(new SupportingFile("client/suite.mustache", outputFolder + "/client", clientName + extension)); + } + + public void run(Map models, Map operations, Map bundle) throws Exception { + Map cts = loadCTS(); + ParametersWithDataType paramsType = new ParametersWithDataType(models, language); + + List blocks = new ArrayList<>(); + for (Map.Entry blockEntry : cts.entrySet()) { + Map testObj = new HashMap<>(); + List tests = new ArrayList<>(); + for (ClientTestData test : blockEntry.getValue()) { + Map testOut = new HashMap<>(); + List steps = new ArrayList<>(); + testOut.put("testName", test.testName); + testOut.put("autoCreateClient", test.autoCreateClient); + for (Step step : test.steps) { + Map stepOut = new HashMap<>(); + if (step.type.equals("createClient")) { + stepOut.put("isCreateClient", true); + } else if (step.type.equals("variable")) { + stepOut.put("isVariable", true); + } else if (step.type.equals("method")) { + stepOut.put("isMethod", true); + } + + stepOut.put("object", step.object); + stepOut.put("path", step.path); + paramsType.enhanceParameters(step.parameters, stepOut); + + switch (step.expected.testSubject) { + case "userAgent": + stepOut.put("testUserAgent", true); + break; + default: + stepOut.put("testSubject", step.expected.testSubject); + } + if (step.expected.error != null) { + stepOut.put("isError", true); + stepOut.put("expectedError", step.expected.error); + } else if (step.expected.match != null) { + Map match = new HashMap<>(); + match.put("regexp", step.expected.match.regexp); + if (step.expected.match.objectContaining != null) { + Map objectContaining = new HashMap<>(); + paramsType.enhanceParameters(step.expected.match.objectContaining, objectContaining); + match.put("objectContaining", objectContaining); + } + stepOut.put("match", match); + } + + steps.add(stepOut); + } + testOut.put("steps", steps); + tests.add(testOut); + } + testObj.put("tests", tests); + testObj.put("testType", blockEntry.getKey()); + blocks.add(testObj); + } + bundle.put("blocksClient", blocks); + } } diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java index 9c709130c11..0abee68837c 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java @@ -79,13 +79,13 @@ public void run(Map models, Map Map requestOptions = new HashMap<>(); if (req.requestOptions.queryParameters != null) { Map queryParameters = new HashMap<>(); - paramsType.enhanceParameters(req.requestOptions.queryParameters, queryParameters, null); + paramsType.enhanceParameters(req.requestOptions.queryParameters, queryParameters); requestOptions.put("queryParameters", queryParameters); } if (req.requestOptions.headers != null) { Map headers = new HashMap<>(); // convert the headers to an acceptable type - paramsType.enhanceParameters(new HashMap(req.requestOptions.headers), headers, null); + paramsType.enhanceParameters(new HashMap(req.requestOptions.headers), headers); requestOptions.put("headers", headers); } test.put("requestOptions", requestOptions); @@ -94,7 +94,7 @@ public void run(Map models, Map CodegenOperation ope = entry.getValue(); // special case if there is only bodyParam which is not an array if (ope.allParams.size() == 1 && ope.bodyParams.size() == 1 && !ope.bodyParam.isArray) { - paramsType.enhanceRootParameters(req.parameters, ope.bodyParam.paramName, ope.bodyParam, test); + paramsType.enhanceParameters(req.parameters, test, ope.bodyParam, ope.bodyParam.paramName); } else { paramsType.enhanceParameters(req.parameters, test, ope); } diff --git a/scripts/__tests__/common.test.ts b/scripts/__tests__/common.test.ts index 43d53ccd3aa..ba88ef8291d 100644 --- a/scripts/__tests__/common.test.ts +++ b/scripts/__tests__/common.test.ts @@ -1,6 +1,6 @@ import execa from 'execa'; -import { gitCommit } from '../common'; +import { capitalize, createClientName, gitCommit } from '../common'; import { getClientsConfigField } from '../config'; jest.mock('execa'); @@ -76,3 +76,42 @@ describe('config', () => { }); }); }); + +describe('utils', () => { + describe('capitalize', () => { + it('should capitalize first letter', () => { + expect(capitalize('hello')).toEqual('Hello'); + expect(capitalize('Hello')).toEqual('Hello'); + }); + + it('should only capitalize first letter', () => { + expect(capitalize('hello wolrd')).toEqual('Hello wolrd'); + expect(capitalize('Hello wolrd')).toEqual('Hello wolrd'); + }); + + it('should not affect other character', () => { + expect(capitalize('8Hello')).toEqual('8Hello'); + expect(capitalize('')).toEqual(''); + }); + }); + + describe('createClientName', () => { + it('does not capitalize every part for JavaScript', () => { + expect(createClientName('search', 'javascript')).toEqual('search'); + expect(createClientName('search-client', 'javascript')).toEqual( + 'searchClient' + ); + expect(createClientName('search-cli!nt-complex', 'javascript')).toEqual( + 'searchCli!ntComplex' + ); + }); + + it('capitalize every part for other languages', () => { + expect(createClientName('search', 'java')).toEqual('Search'); + expect(createClientName('search-client', 'java')).toEqual('SearchClient'); + expect(createClientName('search-cli!nt-complex', 'java')).toEqual( + 'SearchCli!ntComplex' + ); + }); + }); +}); diff --git a/scripts/common.ts b/scripts/common.ts index a2b01bcaa1b..86da81907e6 100644 --- a/scripts/common.ts +++ b/scripts/common.ts @@ -284,3 +284,31 @@ export function wait(waitTime: number): Promise { setTimeout(resolve, waitTime); }); } + +export function createClientName(client: string, language: string): string { + return language === 'javascript' + ? camelize(client) + : capitalize(camelize(client)); +} + +/** + * Splits a string for a given `delimiter` (defaults to `-`) and capitalize each + * parts except the first letter. + * + * `search-client` -> `searchClient`. + */ +export function camelize(str: string, delimiter: string = '-'): string { + return str + .split(delimiter) + .map((part, i) => (i === 0 ? part : capitalize(part))) + .join(''); +} + +/** + * Sets the first letter of the given string in capital. + * + * `searchClient` -> `SearchClient`. + */ +export function capitalize(str: string): string { + return str.charAt(0).toUpperCase() + str.slice(1); +} diff --git a/scripts/cts/client/generate.ts b/scripts/cts/client/generate.ts deleted file mode 100644 index 678060bdaf2..00000000000 --- a/scripts/cts/client/generate.ts +++ /dev/null @@ -1,165 +0,0 @@ -import fsp from 'fs/promises'; - -import Mustache from 'mustache'; - -import { exists, toAbsolutePath } from '../../common'; -import { createSpinner } from '../../oraLog'; -import type { Generator } from '../../types'; -import { - walk, - createOutputDir, - getOutputPath, - loadTemplates, - createClientName, -} from '../utils'; - -import type { TestsBlock, Test, ModifiedStepForMustache } from './types'; - -const testPath = 'client'; - -async function loadTests(client: string): Promise { - const testsBlocks: TestsBlock[] = []; - const clientPath = toAbsolutePath(`tests/CTS/client/${client}`); - - if (!(await exists(clientPath))) { - return []; - } - - for await (const file of walk(clientPath)) { - if (!file.name.endsWith('.json')) { - continue; - } - const fileName = file.name.replace('.json', ''); - const fileContent = (await fsp.readFile(file.path)).toString(); - - if (!fileContent) { - throw new Error(`cannot read empty file ${fileName} - ${client} client`); - } - - const tests: Test[] = JSON.parse(fileContent).map((testCase) => { - if (!testCase.testName) { - throw new Error( - `Cannot have a test with no name ${fileName} - ${client} client` - ); - } - return { - autoCreateClient: true, - ...testCase, - }; - }); - - testsBlocks.push({ - operationId: fileName, - tests, - }); - } - - return testsBlocks.sort((a, b) => a.operationId.localeCompare(b.operationId)); -} - -export async function generateClientTests( - { language, client, additionalProperties }: Generator, - verbose: boolean -): Promise { - let spinner = createSpinner( - { text: 'generating client tests', indent: 4 }, - verbose - ).start(); - const testsBlocks = await loadTests(client); - - await createOutputDir({ language, testPath }); - - if (testsBlocks.length === 0) { - spinner.warn("skipping because tests doesn't exist"); - return; - } - spinner.info(); - spinner = createSpinner( - { text: 'loading templates', indent: 8 }, - verbose - ).start(); - - const { suite: template, ...partialTemplates } = await loadTemplates({ - language, - }); - - if (!template) { - spinner.warn("skipping because template doesn't exist"); - return; - } - - spinner.text = 'rendering templates'; - const code = Mustache.render( - template, - { - import: additionalProperties?.packageName, - client: `${createClientName(client, language)}Client`, - blocks: modifyForMustache(testsBlocks), - hasRegionalHost: additionalProperties?.hasRegionalHost ? true : undefined, - defaultRegion: client === 'predict' ? 'ew' : 'us', - }, - partialTemplates - ); - await fsp.writeFile(getOutputPath({ language, client, testPath }), code); - - spinner.succeed(); -} - -function serializeParameters(parameters: any): string { - const serialized = JSON.stringify(parameters); - return serialized.slice(1, serialized.length - 1); // remove array bracket surrounding the parameters -} - -function modifyForMustache( - blocks: TestsBlock[] -): Array> { - return blocks.map(({ tests, ...blockRest }) => ({ - ...blockRest, - tests: tests.map(({ steps, ...testRest }) => ({ - ...testRest, - steps: steps.map((step) => { - const base = { - isCreateClient: step.type === 'createClient', - isVariable: step.type === 'variable', - isMethod: step.type === 'method', - }; - - let modified: ModifiedStepForMustache; - if (step.type === 'method') { - modified = { - type: step.type, - object: step.object, - path: step.path, - expected: step.expected, - parameters: step.parameters && serializeParameters(step.parameters), - ...base, - }; - } else { - modified = { ...step, ...base }; - } - - if (step.expected?.error) { - modified.expectedError = step.expected.error; - } - - if (step.expected?.error === false) { - modified.expectedNoError = true; - } - - if (step.expected?.match?.objectContaining) { - if (!modified.expected) { - modified.expected = {}; - } - - modified.expected.match = { - objectContaining: JSON.stringify( - step.expected?.match?.objectContaining - ), - }; - } - - return modified; - }), - })), - })); -} diff --git a/scripts/cts/client/types.ts b/scripts/cts/client/types.ts deleted file mode 100644 index 109969f94f0..00000000000 --- a/scripts/cts/client/types.ts +++ /dev/null @@ -1,54 +0,0 @@ -export type Test = { - testName: string; - autoCreateClient?: boolean; // `true` by default - steps: TStep[]; -}; - -export type Step = CreateClientStep | MethodStep | VariableStep; - -export type ModifiedStepForMustache = { - isCreateClient: boolean; - isVariable: boolean; - isMethod: boolean; - expectedError?: string; - expectedNoError?: true; -} & ( - | CreateClientStep - | VariableStep - | (Omit & { parameters: string }) -); - -export type CreateClientStep = { - type: 'createClient'; - parameters: { - appId: string; - apiKey: string; - }; - expected?: Expected; -}; - -type VariableStep = { - type: 'variable'; - object: string; - path: string[]; - expected?: Expected; -}; - -type MethodStep = { - type: 'method'; - object: string; - path: string[]; - parameters?: any; - expected?: Expected; -}; - -type Expected = { - length?: number; - error?: string | false; - match?: any | { objectContaining: Record }; -}; - -export type TestsBlock = { - operationId: string; - tests: Array>; -}; diff --git a/scripts/cts/generate.ts b/scripts/cts/generate.ts index f8847c7ea19..f128b984478 100644 --- a/scripts/cts/generate.ts +++ b/scripts/cts/generate.ts @@ -5,12 +5,9 @@ import { createSpinner } from '../oraLog'; import { generateOpenapitools } from '../pre-gen'; import type { Generator } from '../types'; -import { generateClientTests } from './client/generate'; - async function ctsGenerate(gen: Generator, verbose: boolean): Promise { - createSpinner(`generating CTS for ${gen.key}`, verbose).start().info(); const spinner = createSpinner( - { text: 'generating requests tests', indent: 4 }, + `generating CTS for ${gen.key}`, verbose ).start(); await run( @@ -19,12 +16,6 @@ async function ctsGenerate(gen: Generator, verbose: boolean): Promise { { verbose } ); spinner.succeed(); - switch (gen.language) { - case 'javascript': - await generateClientTests(gen, verbose); - break; - default: - } } export async function ctsGenerateMany( diff --git a/scripts/cts/integrations/.gitkeep b/scripts/cts/integrations/.gitkeep deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/scripts/cts/utils.test.ts b/scripts/cts/utils.test.ts deleted file mode 100644 index 314ddc5d5a8..00000000000 --- a/scripts/cts/utils.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { capitalize, createClientName } from './utils'; - -describe('utils', () => { - describe('capitalize', () => { - it('should capitalize first letter', () => { - expect(capitalize('hello')).toEqual('Hello'); - expect(capitalize('Hello')).toEqual('Hello'); - }); - - it('should only capitalize first letter', () => { - expect(capitalize('hello wolrd')).toEqual('Hello wolrd'); - expect(capitalize('Hello wolrd')).toEqual('Hello wolrd'); - }); - - it('should not affect other character', () => { - expect(capitalize('8Hello')).toEqual('8Hello'); - expect(capitalize('')).toEqual(''); - }); - }); - - describe('createClientName', () => { - it('does not capitalize every part for JavaScript', () => { - expect(createClientName('search', 'javascript')).toEqual('search'); - expect(createClientName('search-client', 'javascript')).toEqual( - 'searchClient' - ); - expect(createClientName('search-cli!nt-complex', 'javascript')).toEqual( - 'searchCli!ntComplex' - ); - }); - - it('capitalize every part for other languages', () => { - expect(createClientName('search', 'java')).toEqual('Search'); - expect(createClientName('search-client', 'java')).toEqual('SearchClient'); - expect(createClientName('search-cli!nt-complex', 'java')).toEqual( - 'SearchCli!ntComplex' - ); - }); - }); -}); diff --git a/scripts/cts/utils.ts b/scripts/cts/utils.ts deleted file mode 100644 index 93b484bb448..00000000000 --- a/scripts/cts/utils.ts +++ /dev/null @@ -1,115 +0,0 @@ -import fsp from 'fs/promises'; -import path from 'path'; - -import { exists, toAbsolutePath } from '../common'; -import { getTestExtension, getTestOutputFolder } from '../config'; -import type { Language } from '../types'; - -export async function* walk( - dir: string -): AsyncGenerator<{ path: string; name: string }> { - for await (const d of await fsp.opendir(dir)) { - const entry = path.join(dir, d.name); - if (d.isDirectory()) yield* walk(entry); - else if (d.isFile()) yield { path: entry, name: d.name }; - } -} - -/** - * Sets the first letter of the given string in capital. - * - * `searchClient` -> `SearchClient`. - */ -export function capitalize(str: string): string { - return str.charAt(0).toUpperCase() + str.slice(1); -} - -/** - * Splits a string for a given `delimiter` (defaults to `-`) and capitalize each - * parts except the first letter. - * - * `search-client` -> `searchClient`. - */ -export function camelize(str: string, delimiter: string = '-'): string { - return str - .split(delimiter) - .map((part, i) => { - if (i === 0) { - return part; - } - - return capitalize(part); - }) - .join(''); -} - -/** - * Returns the client name with the correct casing for its language. - * - * `search-client`, `java` -> `SearchClient`. - * - * `search-client`, `javascript` -> `searchClient`. - */ -export function createClientName(client: string, language: string): string { - if (language === 'javascript') { - return camelize(client); - } - - return capitalize(camelize(client)); -} - -export async function createOutputDir({ - language, - testPath, -}: { - language: Language; - testPath: string; -}): Promise { - await fsp.mkdir( - toAbsolutePath( - `tests/output/${language}/${getTestOutputFolder(language)}/${testPath}` - ), - { - recursive: true, - } - ); -} - -export function getOutputPath({ - language, - client, - testPath, -}: { - language: Language; - client: string; - testPath: string; -}): string { - return toAbsolutePath( - `tests/output/${language}/${getTestOutputFolder( - language - )}/${testPath}/${client}${getTestExtension(language)}` - ); -} - -export async function loadTemplates({ - language, -}: { - language: string; -}): Promise> { - const templates: Record = {}; - const templatePath = toAbsolutePath(`templates/${language}/tests/client`); - - if (!(await exists(templatePath))) { - return {}; - } - - for await (const file of walk(templatePath)) { - if (!file.name.endsWith('.mustache')) { - continue; - } - const name = file.name.replace('.mustache', ''); - const fileContent = (await fsp.readFile(file.path)).toString(); - templates[name] = fileContent; - } - return templates; -} diff --git a/scripts/playground.ts b/scripts/playground.ts index af9157d1c42..45aee0782ba 100644 --- a/scripts/playground.ts +++ b/scripts/playground.ts @@ -1,5 +1,4 @@ -import { run } from './common'; -import { capitalize } from './cts/utils'; +import { createClientName, run } from './common'; import type { Language } from './types'; export async function playground({ @@ -18,8 +17,9 @@ export async function playground({ break; case 'java': await run( - `./gradle/gradlew -p playground/java -PmainClass=com.algolia.playground.${capitalize( - client + `./gradle/gradlew -p playground/java -PmainClass=com.algolia.playground.${createClientName( + client, + 'java' )} run`, { verbose, diff --git a/scripts/pre-gen/removeExistingCodegen.ts b/scripts/pre-gen/removeExistingCodegen.ts index fb609b2f618..6676fa8646a 100644 --- a/scripts/pre-gen/removeExistingCodegen.ts +++ b/scripts/pre-gen/removeExistingCodegen.ts @@ -1,8 +1,7 @@ import path from 'path'; -import { run, toAbsolutePath } from '../common'; +import { createClientName, run, toAbsolutePath } from '../common'; import { getLanguageApiFolder, getLanguageModelFolder } from '../config'; -import { createClientName } from '../cts/utils'; import type { Generator } from '../types'; /** diff --git a/templates/javascript/tests/client/createClient.mustache b/templates/javascript/tests/client/createClient.mustache index cef29eb87f3..cdf475a3bcf 100644 --- a/templates/javascript/tests/client/createClient.mustache +++ b/templates/javascript/tests/client/createClient.mustache @@ -1,3 +1 @@ -{{client}}( - '{{parameters.appId}}','{{parameters.apiKey}}',{{#hasRegionalHost}}'{{parameters.region}}',{{/hasRegionalHost}}{requester: echoRequester()} -) +{{client}}('{{parametersWithDataTypeMap.appId.value}}','{{parametersWithDataTypeMap.apiKey.value}}',{{#hasRegionalHost}}'{{parametersWithDataTypeMap.region.value}}',{{/hasRegionalHost}}{requester: echoRequester()}) \ No newline at end of file diff --git a/templates/javascript/tests/client/expected.mustache b/templates/javascript/tests/client/expected.mustache deleted file mode 100644 index 408fbe57c65..00000000000 --- a/templates/javascript/tests/client/expected.mustache +++ /dev/null @@ -1,13 +0,0 @@ -{{#length}} - expect({{> testSubject}}).toHaveLength({{length}}); -{{/length}} - -{{#match}} - {{#objectContaining}} - expect({{> testSubject}}).toEqual(expect.objectContaining({{{objectContaining}}})); - {{/objectContaining}} - - {{#regexp}} - expect({{> testSubject}}).toMatch({{{regexp}}}); - {{/regexp}} -{{/match}} \ No newline at end of file diff --git a/templates/javascript/tests/client/step.mustache b/templates/javascript/tests/client/step.mustache index d03394f619f..b1726bd73d1 100644 --- a/templates/javascript/tests/client/step.mustache +++ b/templates/javascript/tests/client/step.mustache @@ -1,12 +1,10 @@ {{#isCreateClient}} - $client = {{> createClient}} - actual = $client; + {{> client/createClient}} + const $client = result; {{/isCreateClient}} - {{#isVariable}} - actual = {{> variable}} + {{> client/variable}} {{/isVariable}} - {{#isMethod}} - actual = {{> method}} + await {{> client/method}} {{/isMethod}} \ No newline at end of file diff --git a/templates/javascript/tests/client/suite.mustache b/templates/javascript/tests/client/suite.mustache index 29926a79ea1..a77a79a42e0 100644 --- a/templates/javascript/tests/client/suite.mustache +++ b/templates/javascript/tests/client/suite.mustache @@ -1,69 +1,50 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable require-await */ -/* eslint-disable @typescript-eslint/explicit-function-return-type */ /* eslint-disable prefer-const */ // @ts-nocheck Failing tests will have type errors, but we cannot suppress them even with @ts-expect-error because it doesn't work for a block of lines. -import { {{client}} } from '{{{import}}}'; +import { {{client}}, {{#lambda.titlecase}}{{client}}{{/lambda.titlecase}} } from '{{{import}}}'; import { echoRequester } from '@experimental-api-clients-automation/requester-node-http'; const appId = 'test-app-id'; const apiKey = 'test-api-key'; -// eslint-disable-next-line @typescript-eslint/explicit-function-return-type -function createClient() { +function createClient(): {{#lambda.titlecase}}{{client}}{{/lambda.titlecase}} { return {{client}}(appId, apiKey, {{#hasRegionalHost}}'{{{defaultRegion}}}', {{/hasRegionalHost}}{ requester: echoRequester() }); } -{{#blocks}} -describe('{{operationId}}', () => { +{{#blocksClient}} +describe('{{testType}}', () => { {{#tests}} test('{{{testName}}}', async () => { - let $client; {{#autoCreateClient}} - $client = createClient(); + const $client = createClient(); {{/autoCreateClient}} - let actual; + let result; {{#steps}} - {{#expectedError}} - await expect(new Promise((resolve, reject) => { - {{> step}} - if (actual instanceof Promise) { - actual.then(resolve).catch(reject); - } else { - resolve(); - } - })).rejects.toThrow("{{{expectedError}}}") - {{/expectedError}} - - {{^expectedError}} - {{#expectedNoError}} - await expect(new Promise((resolve, reject) => { - {{> step}} - if (actual instanceof Promise) { - actual.then(resolve).catch(reject); - } else { - resolve(); - } - })).resolves.not.toThrow(); - {{/expectedNoError}} - - {{^expectedNoError}} - {{> step}} - - if (actual instanceof Promise) { - actual = await actual; - } - - {{#expected}} - {{> expected}} - {{/expected}} - {{/expectedNoError}} - {{/expectedError}} + {{#isError}} + try { + result = {{> client/step}} + } catch(e) { + expect(e.message).toMatch("{{{expectedError}}}"); + } + {{/isError}} + {{^isError}} + result = {{> client/step}} + {{#match}} + {{#objectContaining}} + expect({{> client/testSubject}}).toEqual(expect.objectContaining({{{objectContaining.parameters}}})); + {{/objectContaining}} + + {{#regexp}} + expect({{> client/testSubject}}).toMatch({{{regexp}}}); + {{/regexp}} + {{/match}} + {{/isError}} {{/steps}} }); {{/tests}} }) -{{/blocks}} +{{/blocksClient}} diff --git a/templates/javascript/tests/client/testSubject.mustache b/templates/javascript/tests/client/testSubject.mustache index ffa50baad3d..f0a65d715ef 100644 --- a/templates/javascript/tests/client/testSubject.mustache +++ b/templates/javascript/tests/client/testSubject.mustache @@ -1,7 +1,6 @@ +{{#testUserAgent}} + result.algoliaAgent +{{/testUserAgent}} {{#testSubject}} - {{{testSubject}}} -{{/testSubject}} - -{{^testSubject}} - actual + {{{.}}} {{/testSubject}} \ No newline at end of file diff --git a/tests/CTS/client/abtesting/api.json b/tests/CTS/client/abtesting/api.json index 537ea53da35..89ad1662dfc 100644 --- a/tests/CTS/client/abtesting/api.json +++ b/tests/CTS/client/abtesting/api.json @@ -6,20 +6,18 @@ "type": "method", "object": "$client", "path": "addABTests", - "parameters": [ - { - "name": "test", - "variant": [ - { - "index": "my-test-index", - "trafficPercentage": 90 - } - ], - "endAt": "2022-02-01T13:37:01Z" - } - ], + "parameters": { + "name": "test", + "variant": [ + { + "index": "my-test-index", + "trafficPercentage": 90 + } + ], + "endAt": "2022-02-01T13:37:01Z" + }, "expected": { - "testSubject": "actual.algoliaAgent", + "testSubject": "userAgent", "match": { "regexp": "/Algolia%20for%20(.+)%20\\(\\d+\\.\\d+\\.\\d+\\)/" } @@ -34,18 +32,16 @@ "type": "method", "object": "$client", "path": "addABTests", - "parameters": [ - { - "name": "test", - "variant": [ - { - "index": "my-test-index", - "trafficPercentage": 90 - } - ], - "endAt": "2022-02-01T13:37:01Z" - } - ], + "parameters": { + "name": "test", + "variant": [ + { + "index": "my-test-index", + "trafficPercentage": 90 + } + ], + "endAt": "2022-02-01T13:37:01Z" + }, "expected": { "match": { "objectContaining": { diff --git a/tests/CTS/client/abtesting/parameters.json b/tests/CTS/client/abtesting/parameters.json index 545d4199727..21fe66df012 100644 --- a/tests/CTS/client/abtesting/parameters.json +++ b/tests/CTS/client/abtesting/parameters.json @@ -9,19 +9,15 @@ "appId": "my-app-id", "apiKey": "my-api-key" }, - "expected": { - "error": false - } + "expected": {} }, { "type": "method", "object": "$client", "path": "getABTest", - "parameters": [ - { - "id": "test" - } - ], + "parameters": { + "id": "test" + }, "expected": { "match": { "objectContaining": { diff --git a/tests/CTS/client/analytics/api.json b/tests/CTS/client/analytics/api.json index ef76a25f40e..3bd43a63ac9 100644 --- a/tests/CTS/client/analytics/api.json +++ b/tests/CTS/client/analytics/api.json @@ -6,13 +6,11 @@ "type": "method", "object": "$client", "path": "getAverageClickPosition", - "parameters": [ - { - "index": "my-index" - } - ], + "parameters": { + "index": "my-index" + }, "expected": { - "testSubject": "actual.algoliaAgent", + "testSubject": "userAgent", "match": { "regexp": "/Algolia%20for%20(.+)%20\\(\\d+\\.\\d+\\.\\d+\\)/" } @@ -27,11 +25,9 @@ "type": "method", "object": "$client", "path": "getAverageClickPosition", - "parameters": [ - { - "index": "my-index" - } - ], + "parameters": { + "index": "my-index" + }, "expected": { "match": { "objectContaining": { diff --git a/tests/CTS/client/analytics/parameters.json b/tests/CTS/client/analytics/parameters.json index 7a1793fd4dc..7007cb6a44d 100644 --- a/tests/CTS/client/analytics/parameters.json +++ b/tests/CTS/client/analytics/parameters.json @@ -9,19 +9,15 @@ "appId": "my-app-id", "apiKey": "my-api-key" }, - "expected": { - "error": false - } + "expected": {} }, { "type": "method", "object": "$client", "path": "getAverageClickPosition", - "parameters": [ - { - "index": "my-index" - } - ], + "parameters": { + "index": "my-index" + }, "expected": { "match": { "objectContaining": { @@ -39,9 +35,7 @@ "type": "method", "object": "$client", "path": "getClickPositions", - "parameters": [ - {} - ], + "parameters": {}, "expected": { "error": "Parameter `index` is required when calling `getClickPositions`." } diff --git a/tests/CTS/client/insights/api.json b/tests/CTS/client/insights/api.json index 71239eb2c32..6ac6c0669f4 100644 --- a/tests/CTS/client/insights/api.json +++ b/tests/CTS/client/insights/api.json @@ -6,13 +6,11 @@ "type": "method", "object": "$client", "path": "pushEvents", - "parameters": [ - { - "events": [] - } - ], + "parameters": { + "events": [] + }, "expected": { - "testSubject": "actual.algoliaAgent", + "testSubject": "userAgent", "match": { "regexp": "/Algolia%20for%20(.+)%20\\(\\d+\\.\\d+\\.\\d+\\)/" } @@ -27,11 +25,9 @@ "type": "method", "object": "$client", "path": "pushEvents", - "parameters": [ - { - "events": [] - } - ], + "parameters": { + "events": [] + }, "expected": { "match": { "objectContaining": { diff --git a/tests/CTS/client/insights/parameters.json b/tests/CTS/client/insights/parameters.json index 24e08c48d42..71a503f199d 100644 --- a/tests/CTS/client/insights/parameters.json +++ b/tests/CTS/client/insights/parameters.json @@ -9,19 +9,15 @@ "appId": "my-app-id", "apiKey": "my-api-key" }, - "expected": { - "error": false - } + "expected": {} }, { "type": "method", "object": "$client", "path": "pushEvents", - "parameters": [ - { - "events": [] - } - ], + "parameters": { + "events": [] + }, "expected": { "match": { "objectContaining": { diff --git a/tests/CTS/client/personalization/api.json b/tests/CTS/client/personalization/api.json index 4d3c29e1ada..4ba8964f7f0 100644 --- a/tests/CTS/client/personalization/api.json +++ b/tests/CTS/client/personalization/api.json @@ -6,9 +6,9 @@ "type": "method", "object": "$client", "path": "getPersonalizationStrategy", - "parameters": [], + "parameters": {}, "expected": { - "testSubject": "actual.algoliaAgent", + "testSubject": "userAgent", "match": { "regexp": "/Algolia%20for%20(.+)%20\\(\\d+\\.\\d+\\.\\d+\\)/" } @@ -23,7 +23,7 @@ "type": "method", "object": "$client", "path": "getPersonalizationStrategy", - "parameters": [], + "parameters": {}, "expected": { "match": { "objectContaining": { diff --git a/tests/CTS/client/personalization/parameters.json b/tests/CTS/client/personalization/parameters.json index 5f097fb0ab4..ef5383aad66 100644 --- a/tests/CTS/client/personalization/parameters.json +++ b/tests/CTS/client/personalization/parameters.json @@ -27,9 +27,7 @@ "apiKey": "my-api-key", "region": "us" }, - "expected": { - "error": false - } + "expected": {} } ] } diff --git a/tests/CTS/client/predict/api.json b/tests/CTS/client/predict/api.json index f2d0632b1c4..b6653d2f64d 100644 --- a/tests/CTS/client/predict/api.json +++ b/tests/CTS/client/predict/api.json @@ -6,18 +6,16 @@ "type": "method", "object": "$client", "path": "fetchUserProfile", - "parameters": [ - { - "userID": "user1", - "params": { - "modelsToRetrieve": [ - "funnel_stage" - ] - } + "parameters": { + "userID": "user1", + "params": { + "modelsToRetrieve": [ + "funnel_stage" + ] } - ], + }, "expected": { - "testSubject": "actual.algoliaAgent", + "testSubject": "userAgent", "match": { "regexp": "/Algolia%20for%20(.+)%20\\(\\d+\\.\\d+\\.\\d+\\)/" } @@ -32,16 +30,14 @@ "type": "method", "object": "$client", "path": "fetchUserProfile", - "parameters": [ - { - "userID": "user1", - "params": { - "modelsToRetrieve": [ - "funnel_stage" - ] - } + "parameters": { + "userID": "user1", + "params": { + "modelsToRetrieve": [ + "funnel_stage" + ] } - ], + }, "expected": { "match": { "objectContaining": { diff --git a/tests/CTS/client/predict/parameters.json b/tests/CTS/client/predict/parameters.json index 1f7d52ac64e..da177609d4d 100644 --- a/tests/CTS/client/predict/parameters.json +++ b/tests/CTS/client/predict/parameters.json @@ -27,9 +27,7 @@ "apiKey": "my-api-key", "region": "ew" }, - "expected": { - "error": false - } + "expected": {} } ] } diff --git a/tests/CTS/client/query-suggestions/api.json b/tests/CTS/client/query-suggestions/api.json index da59a8a5f86..919a72c4122 100644 --- a/tests/CTS/client/query-suggestions/api.json +++ b/tests/CTS/client/query-suggestions/api.json @@ -6,11 +6,9 @@ "type": "method", "object": "$client", "path": "createConfig", - "parameters": [ - {} - ], + "parameters": {}, "expected": { - "testSubject": "actual.algoliaAgent", + "testSubject": "userAgent", "match": { "regexp": "/Algolia%20for%20(.+)%20\\(\\d+\\.\\d+\\.\\d+\\)/" } @@ -25,9 +23,7 @@ "type": "method", "object": "$client", "path": "createConfig", - "parameters": [ - {} - ], + "parameters": {}, "expected": { "match": { "objectContaining": { diff --git a/tests/CTS/client/query-suggestions/parameters.json b/tests/CTS/client/query-suggestions/parameters.json index 5f097fb0ab4..ef5383aad66 100644 --- a/tests/CTS/client/query-suggestions/parameters.json +++ b/tests/CTS/client/query-suggestions/parameters.json @@ -27,9 +27,7 @@ "apiKey": "my-api-key", "region": "us" }, - "expected": { - "error": false - } + "expected": {} } ] } diff --git a/tests/CTS/client/recommend/api.json b/tests/CTS/client/recommend/api.json index 038ffa8d1a1..da0839a28af 100644 --- a/tests/CTS/client/recommend/api.json +++ b/tests/CTS/client/recommend/api.json @@ -6,11 +6,9 @@ "type": "method", "object": "$client", "path": "getRecommendations", - "parameters": [ - { - "requests": [] - } - ], + "parameters": { + "requests": [] + }, "expected": { "match": { "objectContaining": { @@ -28,13 +26,11 @@ "type": "method", "object": "$client", "path": "getRecommendations", - "parameters": [ - { - "requests": [] - } - ], + "parameters": { + "requests": [] + }, "expected": { - "testSubject": "actual.algoliaAgent", + "testSubject": "userAgent", "match": { "regexp": "/Algolia%20for%20(.+)%20\\(\\d+\\.\\d+\\.\\d+\\)/" } @@ -49,11 +45,9 @@ "type": "method", "object": "$client", "path": "getRecommendations", - "parameters": [ - { - "requests": [] - } - ], + "parameters": { + "requests": [] + }, "expected": { "match": { "objectContaining": { diff --git a/tests/CTS/client/search/api.json b/tests/CTS/client/search/api.json index 0b2c331e2c1..2c708b21c84 100644 --- a/tests/CTS/client/search/api.json +++ b/tests/CTS/client/search/api.json @@ -6,15 +6,13 @@ "type": "method", "object": "$client", "path": "search", - "parameters": [ - { - "requests": [ - { - "indexName": "my-index" - } - ] - } - ], + "parameters": { + "requests": [ + { + "indexName": "my-index" + } + ] + }, "expected": { "match": { "objectContaining": { @@ -32,17 +30,15 @@ "type": "method", "object": "$client", "path": "search", - "parameters": [ - { - "requests": [ - { - "indexName": "my-index" - } - ] - } - ], + "parameters": { + "requests": [ + { + "indexName": "my-index" + } + ] + }, "expected": { - "testSubject": "actual.algoliaAgent", + "testSubject": "userAgent", "match": { "regexp": "/Algolia%20for%20(.+)%20\\(\\d+\\.\\d+\\.\\d+\\)/" } @@ -57,15 +53,13 @@ "type": "method", "object": "$client", "path": "search", - "parameters": [ - { - "requests": [ - { - "indexName": "my-index" - } - ] - } - ], + "parameters": { + "requests": [ + { + "indexName": "my-index" + } + ] + }, "expected": { "match": { "objectContaining": { diff --git a/tests/CTS/client/search/parameters.json b/tests/CTS/client/search/parameters.json index 4c220b22fe4..d6a869d201a 100644 --- a/tests/CTS/client/search/parameters.json +++ b/tests/CTS/client/search/parameters.json @@ -44,9 +44,7 @@ "type": "method", "object": "$client", "path": "addApiKey", - "parameters": [ - {} - ], + "parameters": {}, "expected": { "error": "Parameter `apiKey.acl` is required when calling `addApiKey`." } @@ -60,12 +58,10 @@ "type": "method", "object": "$client", "path": "addOrUpdateObject", - "parameters": [ - { - "objectID": "my-object-id", - "body": {} - } - ], + "parameters": { + "objectID": "my-object-id", + "body": {} + }, "expected": { "error": "Parameter `indexName` is required when calling `addOrUpdateObject`." } @@ -74,12 +70,10 @@ "type": "method", "object": "$client", "path": "addOrUpdateObject", - "parameters": [ - { - "indexName": "my-index-name", - "body": {} - } - ], + "parameters": { + "indexName": "my-index-name", + "body": {} + }, "expected": { "error": "Parameter `objectID` is required when calling `addOrUpdateObject`." } @@ -88,12 +82,10 @@ "type": "method", "object": "$client", "path": "addOrUpdateObject", - "parameters": [ - { - "indexName": "my-index-name", - "objectID": "my-object-id" - } - ], + "parameters": { + "indexName": "my-index-name", + "objectID": "my-object-id" + }, "expected": { "error": "Parameter `body` is required when calling `addOrUpdateObject`." } diff --git a/tests/CTS/client/sources/api.json b/tests/CTS/client/sources/api.json index 4dbd7b51850..c9ca3c53c8a 100644 --- a/tests/CTS/client/sources/api.json +++ b/tests/CTS/client/sources/api.json @@ -6,19 +6,17 @@ "type": "method", "object": "$client", "path": "postIngestUrl", - "parameters": [ - { - "type": "csv", - "input": { - "url": "https://example.com/file.csv" - }, - "target": { - "type": "search", - "indexName": "pageviews", - "operation": "replace" - } + "parameters": { + "type": "csv", + "input": { + "url": "https://example.com/file.csv" + }, + "target": { + "type": "search", + "indexName": "pageviews", + "operation": "replace" } - ], + }, "expected": { "match": { "objectContaining": { @@ -36,21 +34,19 @@ "type": "method", "object": "$client", "path": "postIngestUrl", - "parameters": [ - { - "type": "csv", - "input": { - "url": "https://example.com/file.csv" - }, - "target": { - "type": "search", - "indexName": "pageviews", - "operation": "replace" - } + "parameters": { + "type": "csv", + "input": { + "url": "https://example.com/file.csv" + }, + "target": { + "type": "search", + "indexName": "pageviews", + "operation": "replace" } - ], + }, "expected": { - "testSubject": "actual.algoliaAgent", + "testSubject": "userAgent", "match": { "regexp": "/Algolia%20for%20(.+)%20\\(\\d+\\.\\d+\\.\\d+\\)/" } @@ -65,19 +61,17 @@ "type": "method", "object": "$client", "path": "postIngestUrl", - "parameters": [ - { - "type": "csv", - "input": { - "url": "https://example.com/file.csv" - }, - "target": { - "type": "search", - "indexName": "pageviews", - "operation": "replace" - } + "parameters": { + "type": "csv", + "input": { + "url": "https://example.com/file.csv" + }, + "target": { + "type": "search", + "indexName": "pageviews", + "operation": "replace" } - ], + }, "expected": { "match": { "objectContaining": { diff --git a/tests/CTS/client/sources/parameters.json b/tests/CTS/client/sources/parameters.json index 5f097fb0ab4..ef5383aad66 100644 --- a/tests/CTS/client/sources/parameters.json +++ b/tests/CTS/client/sources/parameters.json @@ -27,9 +27,7 @@ "apiKey": "my-api-key", "region": "us" }, - "expected": { - "error": false - } + "expected": {} } ] } From 34ad4f4b0e351bd8897bf9fcff1f1b790216f871 Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Wed, 1 Jun 2022 19:15:39 +0200 Subject: [PATCH 2/7] fail if no cts --- .../algolia/codegen/cts/AlgoliaCTSGenerator.java | 14 +++++++++++++- .../com/algolia/codegen/cts/tests/TestsClient.java | 5 +++++ .../algolia/codegen/cts/tests/TestsRequest.java | 5 +++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java b/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java index d77d8b6f5ef..bb222e8ae16 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java +++ b/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java @@ -98,7 +98,19 @@ public Map postProcessSupportingFileData(Map obj ctsManager.addDataToBundle(bundle); for (TestsGenerator testGen : testsGenerators) { - testGen.run(models, operations, bundle); + try { + testGen.run(models, operations, bundle); + } catch (CTSException e) { + if (e.isSkipable()) { + System.out.println(e.getMessage()); + System.exit(0); + } + e.printStackTrace(); + System.exit(1); + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } } return bundle; 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 b056593f42f..6fc4da2713a 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 @@ -30,6 +30,11 @@ private Map loadCTS() throws Exception { throw new CTSException("Don't generate test for algoliasearch-lite for now", true); } + File templates = new File("templates/" + language + "/tests/client/suite.mustache"); + if (!templates.exists()) { + throw new CTSException("Templates not found for client test at: " + templates.getAbsolutePath(), true); + } + File dir = new File("tests/CTS/client/" + clientName); if (!dir.exists()) { throw new CTSException("CTS not found at " + dir.getAbsolutePath(), true); diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java index 0abee68837c..56a751d9a14 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java @@ -27,6 +27,11 @@ private Map loadCTS() throws Exception { clientName = "search"; } + File templates = new File("templates/" + language + "/tests/requests/requests.mustache"); + if (!templates.exists()) { + throw new CTSException("Templates not found for requests test at: " + templates.getAbsolutePath(), true); + } + File dir = new File("tests/CTS/methods/requests/" + clientName); File commonTestDir = new File("tests/CTS/methods/requests/common"); if (!dir.exists()) { From 4915251be3ecb0bffc8faf4bb863ad07197fa10f Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Wed, 1 Jun 2022 19:57:18 +0200 Subject: [PATCH 3/7] index steps --- .../codegen/cts/tests/ClientTestData.java | 2 +- .../codegen/cts/tests/TestsClient.java | 19 ++++++++++++------- .../javascript/tests/client/step.mustache | 8 ++++---- .../javascript/tests/client/suite.mustache | 8 +++----- 4 files changed, 20 insertions(+), 17 deletions(-) diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/ClientTestData.java b/generators/src/main/java/com/algolia/codegen/cts/tests/ClientTestData.java index 4ec916d07ff..9e1c24f2fd0 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/tests/ClientTestData.java +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/ClientTestData.java @@ -23,7 +23,7 @@ class Expected { public Object error; public Match match; - public String testSubject = "result"; + public String testSubject; } class Match { 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 6fc4da2713a..d1de97a881d 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 @@ -64,6 +64,7 @@ public void run(Map models, Map List steps = new ArrayList<>(); testOut.put("testName", test.testName); testOut.put("autoCreateClient", test.autoCreateClient); + int stepIndex = 0; for (Step step : test.steps) { Map stepOut = new HashMap<>(); if (step.type.equals("createClient")) { @@ -78,12 +79,16 @@ public void run(Map models, Map stepOut.put("path", step.path); paramsType.enhanceParameters(step.parameters, stepOut); - switch (step.expected.testSubject) { - case "userAgent": - stepOut.put("testUserAgent", true); - break; - default: - stepOut.put("testSubject", step.expected.testSubject); + if (step.expected.testSubject == null) { + stepOut.put("testSubject", "result" + stepIndex); + } else { + switch (step.expected.testSubject) { + case "userAgent": + stepOut.put("testUserAgent", true); + break; + default: + stepOut.put("testSubject", step.expected.testSubject); + } } if (step.expected.error != null) { stepOut.put("isError", true); @@ -98,7 +103,7 @@ public void run(Map models, Map } stepOut.put("match", match); } - + stepOut.put("stepIndex", stepIndex++); steps.add(stepOut); } testOut.put("steps", steps); diff --git a/templates/javascript/tests/client/step.mustache b/templates/javascript/tests/client/step.mustache index b1726bd73d1..87556679b4e 100644 --- a/templates/javascript/tests/client/step.mustache +++ b/templates/javascript/tests/client/step.mustache @@ -1,10 +1,10 @@ {{#isCreateClient}} - {{> client/createClient}} - const $client = result; + const result{{stepIndex}} = {{> client/createClient}} + const $client = result{{stepIndex}}; {{/isCreateClient}} {{#isVariable}} - {{> client/variable}} + const result{{stepIndex}} = {{> client/variable}} {{/isVariable}} {{#isMethod}} - await {{> client/method}} + const result{{stepIndex}} = await {{> client/method}} {{/isMethod}} \ No newline at end of file diff --git a/templates/javascript/tests/client/suite.mustache b/templates/javascript/tests/client/suite.mustache index a77a79a42e0..62533431aa0 100644 --- a/templates/javascript/tests/client/suite.mustache +++ b/templates/javascript/tests/client/suite.mustache @@ -1,6 +1,5 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable require-await */ -/* eslint-disable prefer-const */ // @ts-nocheck Failing tests will have type errors, but we cannot suppress them even with @ts-expect-error because it doesn't work for a block of lines. import { {{client}}, {{#lambda.titlecase}}{{client}}{{/lambda.titlecase}} } from '{{{import}}}'; import { echoRequester } from '@experimental-api-clients-automation/requester-node-http'; @@ -20,17 +19,16 @@ describe('{{testType}}', () => { const $client = createClient(); {{/autoCreateClient}} - let result; {{#steps}} {{#isError}} try { - result = {{> client/step}} + {{> client/step}} } catch(e) { expect(e.message).toMatch("{{{expectedError}}}"); } {{/isError}} - {{^isError}} - result = {{> client/step}} + {{^isError}} + {{> client/step}} {{#match}} {{#objectContaining}} expect({{> client/testSubject}}).toEqual(expect.objectContaining({{{objectContaining.parameters}}})); From 4a18675fa76272ef6a5fc0714be589d5b4533a0d Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Thu, 2 Jun 2022 10:10:46 +0200 Subject: [PATCH 4/7] continue on skippable error --- .../algolia/codegen/cts/AlgoliaCTSGenerator.java | 2 +- .../com/algolia/codegen/cts/tests/TestsClient.java | 14 +++++++++++--- .../algolia/codegen/cts/tests/TestsGenerator.java | 2 ++ .../algolia/codegen/cts/tests/TestsRequest.java | 14 +++++++++++--- 4 files changed, 25 insertions(+), 7 deletions(-) diff --git a/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java b/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java index bb222e8ae16..33a52ec7c52 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java +++ b/generators/src/main/java/com/algolia/codegen/cts/AlgoliaCTSGenerator.java @@ -103,7 +103,7 @@ public Map postProcessSupportingFileData(Map obj } catch (CTSException e) { if (e.isSkipable()) { System.out.println(e.getMessage()); - System.exit(0); + continue; } e.printStackTrace(); System.exit(1); 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 d1de97a881d..687f46734d5 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 @@ -30,9 +30,8 @@ private Map loadCTS() throws Exception { throw new CTSException("Don't generate test for algoliasearch-lite for now", true); } - File templates = new File("templates/" + language + "/tests/client/suite.mustache"); - if (!templates.exists()) { - throw new CTSException("Templates not found for client test at: " + templates.getAbsolutePath(), true); + if (!available()) { + throw new CTSException("Templates not found for client test", true); } File dir = new File("tests/CTS/client/" + clientName); @@ -45,8 +44,17 @@ private Map loadCTS() throws Exception { return cts; } + @Override + public boolean available() { + File templates = new File("templates/" + language + "/tests/client/suite.mustache"); + return templates.exists(); + } + @Override public void addSupportingFiles(List supportingFiles, String outputFolder, String extension) { + if (!available()) { + return; + } String clientName = language.equals("php") ? Utils.createClientName(client, language) : client; supportingFiles.add(new SupportingFile("client/suite.mustache", outputFolder + "/client", clientName + extension)); } diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsGenerator.java b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsGenerator.java index 30ea2c28f5e..aedbbcef220 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsGenerator.java +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsGenerator.java @@ -7,6 +7,8 @@ import org.openapitools.codegen.SupportingFile; public interface TestsGenerator { + public boolean available(); + public void addSupportingFiles(List supportingFiles, String outputFolder, String extension); public void run(Map models, Map operations, Map bundle) throws Exception; diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java index 56a751d9a14..26ca2ccf866 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsRequest.java @@ -27,9 +27,8 @@ private Map loadCTS() throws Exception { clientName = "search"; } - File templates = new File("templates/" + language + "/tests/requests/requests.mustache"); - if (!templates.exists()) { - throw new CTSException("Templates not found for requests test at: " + templates.getAbsolutePath(), true); + if (!available()) { + throw new CTSException("Templates not found for requests test", true); } File dir = new File("tests/CTS/methods/requests/" + clientName); @@ -49,8 +48,17 @@ private Map loadCTS() throws Exception { return cts; } + @Override + public boolean available() { + File templates = new File("templates/" + language + "/tests/requests/requests.mustache"); + return templates.exists(); + } + @Override public void addSupportingFiles(List supportingFiles, String outputFolder, String extension) { + if (!available()) { + return; + } String clientName = language.equals("php") ? Utils.createClientName(client, language) : client; supportingFiles.add(new SupportingFile("requests/requests.mustache", outputFolder + "/methods/requests", clientName + extension)); } From b55b8f77331dd432c6e0f7f407ee8fab961a5f1b Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Thu, 2 Jun 2022 11:25:44 +0200 Subject: [PATCH 5/7] fix mustache --- templates/javascript/tests/client/testSubject.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/javascript/tests/client/testSubject.mustache b/templates/javascript/tests/client/testSubject.mustache index f0a65d715ef..8c2f2c506bc 100644 --- a/templates/javascript/tests/client/testSubject.mustache +++ b/templates/javascript/tests/client/testSubject.mustache @@ -1,5 +1,5 @@ {{#testUserAgent}} - result.algoliaAgent + result{{stepIndex}}.algoliaAgent {{/testUserAgent}} {{#testSubject}} {{{.}}} From 8096309208e94e69f5418129a0d70fa44cbd24ef Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Thu, 2 Jun 2022 11:48:42 +0200 Subject: [PATCH 6/7] =?UTF-8?q?don't=20create=20the=20supporting=20file?= =?UTF-8?q?=C3=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../algolia/codegen/cts/tests/TestsClient.java | 16 +++++++--------- .../tests/client/createClient.mustache | 2 +- templates/javascript/tests/client/step.mustache | 3 +-- 3 files changed, 9 insertions(+), 12 deletions(-) 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 687f46734d5..05ac9191a2a 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 @@ -22,22 +22,15 @@ public TestsClient(String language, String client) { } private Map loadCTS() throws Exception { - Map cts = new HashMap<>(); - String clientName = client; - // This special case allow us to read the `search` CTS to generated the tests for the - // `algoliasearch-lite` client, which is only available in JavaScript - if (language.equals("javascript") && client.equals("algoliasearch-lite")) { - throw new CTSException("Don't generate test for algoliasearch-lite for now", true); - } - if (!available()) { throw new CTSException("Templates not found for client test", true); } - File dir = new File("tests/CTS/client/" + clientName); + File dir = new File("tests/CTS/client/" + client); if (!dir.exists()) { throw new CTSException("CTS not found at " + dir.getAbsolutePath(), true); } + Map cts = new HashMap<>(); for (File f : dir.listFiles()) { cts.put(f.getName().replace(".json", ""), Json.mapper().readValue(f, ClientTestData[].class)); } @@ -46,6 +39,11 @@ private Map loadCTS() throws Exception { @Override public boolean available() { + // no algoliasearch-lite client test for now + if (language.equals("javascript") && client.equals("algoliasearch-lite")) { + return false; + } + File templates = new File("templates/" + language + "/tests/client/suite.mustache"); return templates.exists(); } diff --git a/templates/javascript/tests/client/createClient.mustache b/templates/javascript/tests/client/createClient.mustache index cdf475a3bcf..70c398270c8 100644 --- a/templates/javascript/tests/client/createClient.mustache +++ b/templates/javascript/tests/client/createClient.mustache @@ -1 +1 @@ -{{client}}('{{parametersWithDataTypeMap.appId.value}}','{{parametersWithDataTypeMap.apiKey.value}}',{{#hasRegionalHost}}'{{parametersWithDataTypeMap.region.value}}',{{/hasRegionalHost}}{requester: echoRequester()}) \ No newline at end of file +{{^autoCreateClient}}const $client = {{/autoCreateClient}}{{client}}('{{parametersWithDataTypeMap.appId.value}}','{{parametersWithDataTypeMap.apiKey.value}}',{{#hasRegionalHost}}'{{parametersWithDataTypeMap.region.value}}',{{/hasRegionalHost}}{requester: echoRequester()}); \ No newline at end of file diff --git a/templates/javascript/tests/client/step.mustache b/templates/javascript/tests/client/step.mustache index 87556679b4e..ef6eda13f22 100644 --- a/templates/javascript/tests/client/step.mustache +++ b/templates/javascript/tests/client/step.mustache @@ -1,6 +1,5 @@ {{#isCreateClient}} - const result{{stepIndex}} = {{> client/createClient}} - const $client = result{{stepIndex}}; + {{> client/createClient}} {{/isCreateClient}} {{#isVariable}} const result{{stepIndex}} = {{> client/variable}} From a2b4064f561ef5f9bcaf1e25b5ece9a07fd6a321 Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Thu, 2 Jun 2022 17:45:18 +0200 Subject: [PATCH 7/7] fail if no throw --- templates/javascript/tests/client/suite.mustache | 1 + 1 file changed, 1 insertion(+) diff --git a/templates/javascript/tests/client/suite.mustache b/templates/javascript/tests/client/suite.mustache index 62533431aa0..8985bd01673 100644 --- a/templates/javascript/tests/client/suite.mustache +++ b/templates/javascript/tests/client/suite.mustache @@ -23,6 +23,7 @@ describe('{{testType}}', () => { {{#isError}} try { {{> client/step}} + throw new Error('test is expected to throw error'); } catch(e) { expect(e.message).toMatch("{{{expectedError}}}"); }