diff --git a/.gitignore b/.gitignore index a73007c3ad5..2b1fa3629b0 100644 --- a/.gitignore +++ b/.gitignore @@ -30,7 +30,6 @@ packages/ .vagrant/ .vscode/ **/.vs -bin .factorypath .settings diff --git a/README.md b/README.md index 399e8170700..f1b0d14430b 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se | | Languages/Frameworks | |-|-| -**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Dart (1.x, 2.x)**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node, Rxjs) +**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Dart (1.x, 2.x)**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node, Rxjs) **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc** **Configuration files** | [**Apache2**](https://httpd.apache.org/) @@ -871,6 +871,7 @@ Here is a list of template creators: * Confluence Wiki: @jhitchcock * Configuration * Apache2: @stkrwork + * k6: @mostafa * Schema * Avro: @sgadouar * GraphQL: @wing328 [:heart:](https://www.patreon.com/wing328) diff --git a/bin/windows/k6-petstore.bat b/bin/windows/k6-petstore.bat new file mode 100755 index 00000000000..098a050214e --- /dev/null +++ b/bin/windows/k6-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g k6 -o samples\client\petstore\k6 + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/docs/generators.md b/docs/generators.md index 7c8be859932..c8dd81b0cc7 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -37,7 +37,7 @@ The following generators are available: * [javascript-flowtyped](generators/javascript-flowtyped.md) * [jaxrs-cxf-client](generators/jaxrs-cxf-client.md) * [jmeter](generators/jmeter.md) -* [k6](generators/k6.md) +* [k6 (beta)](generators/k6.md) * [kotlin](generators/kotlin.md) * [lua](generators/lua.md) * [nim (beta)](generators/nim.md) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/k6Codegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java similarity index 92% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/k6Codegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java index 7700702ab83..f5e45947cac 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/k6Codegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java @@ -1,14 +1,34 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.openapitools.codegen.languages; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.PathItem; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.parameters.RequestBody; import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.oas.models.servers.Server; -import org.openapitools.codegen.*; -import io.swagger.v3.oas.models.*; import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; import org.openapitools.codegen.utils.ModelUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,7 +39,16 @@ import java.util.*; import static org.openapitools.codegen.utils.StringUtils.*; -public class k6Codegen extends DefaultCodegen implements CodegenConfig { +public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { + + public K6ClientCodegen() { + super(); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + } static class Parameter { String key; @@ -75,9 +104,9 @@ public class k6Codegen extends DefaultCodegen implements CodegenConfig { String responseType; public HTTPParameters(@Nullable String auth, @Nullable List cookies, - @Nullable List headers, @Nullable List jar, @Nullable Integer redirects, - @Nullable List tags, @Nullable Integer timeout, @Nullable String compression, - @Nullable String responseType) { + @Nullable List headers, @Nullable List jar, @Nullable Integer redirects, + @Nullable List tags, @Nullable Integer timeout, @Nullable String compression, + @Nullable String responseType) { this.auth = auth; this.cookies = cookies; this.headers = headers; @@ -113,7 +142,7 @@ public class k6Codegen extends DefaultCodegen implements CodegenConfig { List k6Checks; public HTTPRequest(String method, String path, @Nullable List query, @Nullable HTTPBody body, - @Nullable HTTPParameters params, @Nullable List k6Checks) { + @Nullable HTTPParameters params, @Nullable List k6Checks) { this.method = method; this.path = path; this.query = query; @@ -144,8 +173,8 @@ public class k6Codegen extends DefaultCodegen implements CodegenConfig { public static final String BASE_URL = "baseURL"; public static final String PRESERVE_LEADING_PARAM_CHAR = "preserveLeadingParamChar"; static final Collection INVOKER_PKG_SUPPORTING_FILES = Arrays.asList("script.mustache", "README.mustache"); - static final String[][] JAVASCRIPT_SUPPORTING_FILES = new String[][] { - new String[] { "script.mustache", "script.js" }, new String[] { "README.mustache", "README.md" } }; + static final String[][] JAVASCRIPT_SUPPORTING_FILES = new String[][]{ + new String[]{"script.mustache", "script.js"}, new String[]{"README.mustache", "README.md"}}; protected String projectName; protected String moduleName; @@ -171,7 +200,7 @@ public class k6Codegen extends DefaultCodegen implements CodegenConfig { @Override public String getHelp() { - return "Generates k6 script."; + return "Generates a k6 script (beta)."; } @Override @@ -402,7 +431,8 @@ public class k6Codegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile(templateFile, folder, supportingTemplateFile[1])); } } -// + + // private String generateNestedModelTemplate(CodegenModel model) { StringBuilder reference = new StringBuilder(); int modelEntrySetSize = model.getAllVars().size(); @@ -430,13 +460,13 @@ public class k6Codegen extends DefaultCodegen implements CodegenConfig { /** * Concatenates an array of path segments into a path string. - * + * * @param segments The path segments to concatenate. A segment may contain * either of the file separator characters '\' or '/'. A segment * is ignored if it is null, empty or * ".". * @return A path string using the correct platform-specific file separator - * character. + * character. */ private String createPath(String... segments) { StringBuilder buf = new StringBuilder(); diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index f42681ca2ed..c48f628a3aa 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -63,7 +63,7 @@ org.openapitools.codegen.languages.JavascriptClientCodegen org.openapitools.codegen.languages.JavascriptFlowtypedClientCodegen org.openapitools.codegen.languages.JavascriptClosureAngularClientCodegen org.openapitools.codegen.languages.JMeterClientCodegen -org.openapitools.codegen.languages.k6Codegen +org.openapitools.codegen.languages.K6ClientCodegen org.openapitools.codegen.languages.LuaClientCodegen org.openapitools.codegen.languages.MysqlSchemaCodegen org.openapitools.codegen.languages.NimClientCodegen diff --git a/modules/openapi-generator/src/main/resources/k6/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/k6/licenseInfo.mustache index b54f89b1fc4..009d1da5062 100644 --- a/modules/openapi-generator/src/main/resources/k6/licenseInfo.mustache +++ b/modules/openapi-generator/src/main/resources/k6/licenseInfo.mustache @@ -9,7 +9,7 @@ * Contact: {{infoEmail}} {{/infoEmail}} * - * NOTE: This class is auto generated by the swagger code generator program. + * NOTE: This class is auto generated by OpenAPI Generator. * https://github.com/OpenAPITools/openapi-generator * * OpenAPI generator version: {{generatorVersion}} diff --git a/samples/client/petstore/k6/script.js b/samples/client/petstore/k6/script.js index afe0b99ef11..cc201350643 100644 --- a/samples/client/petstore/k6/script.js +++ b/samples/client/petstore/k6/script.js @@ -4,10 +4,10 @@ * * OpenAPI spec version: 1.0.0 * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git + * NOTE: This class is auto generated by OpenAPI Generator. + * https://github.com/OpenAPITools/openapi-generator * - * Swagger Codegen version: 4.3.0-SNAPSHOT + * OpenAPI generator version: 4.3.0-SNAPSHOT */ diff --git a/samples/config/petstore/k6/.openapi-generator-ignore b/samples/config/petstore/k6/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/config/petstore/k6/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/config/petstore/k6/.openapi-generator/VERSION b/samples/config/petstore/k6/.openapi-generator/VERSION new file mode 100644 index 00000000000..bfbf77eb7fa --- /dev/null +++ b/samples/config/petstore/k6/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/config/petstore/k6/README.md b/samples/config/petstore/k6/README.md new file mode 100644 index 00000000000..c76d4a6de34 --- /dev/null +++ b/samples/config/petstore/k6/README.md @@ -0,0 +1,13 @@ +# Generated k6 script + +The `script.js` file contains most of the Swagger/OpenAPI specification and you can customize it to your needs. + +Global header variables are defined at the top of the file, like `api_key`. Each path in the specification is converted into a [group](https://docs.k6.io/docs/tags-and-groups) in k6 and each group contains all the request methods related to that path. Path and query parameters are extracted from the specification and put at the start of the group. The URL is constructed from the base URL plus path and query. + +k6 specific parameters are in the [`params`](https://docs.k6.io/docs/params-k6http) object, and `body` contains the [request](https://docs.k6.io/docs/http-requests) body which is in the form of `identifier: type`, which the `type` should be substituted by a proper value. Then goes the request and the check. + +[Check](https://docs.k6.io/docs/checks) are like asserts but differ in that they don't halt execution, instead they just store the result of the check, pass or fail, and let the script execution continue. + +Each request is always followed by a 0.1 second [sleep](https://docs.k6.io/docs/sleep-t-1) to prevent the script execution from flooding the system with too many requests simultaneously. + +Note that the default iteration count and VU count is 1. So each request in each group will be executed once. For more information, see the [k6 options](https://docs.k6.io/docs/options). diff --git a/samples/config/petstore/k6/script.js b/samples/config/petstore/k6/script.js new file mode 100644 index 00000000000..efb3797eeb7 --- /dev/null +++ b/samples/config/petstore/k6/script.js @@ -0,0 +1,204 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/OpenAPITools/openapi-generator + * + * OpenAPI generator version: 4.3.0-SNAPSHOT + */ + + +import http from "k6/http"; +import { group, check, sleep } from "k6"; + +const BASE_URL = "http://petstore.swagger.io/v2"; +// Sleep duration between successive requests. +// You might want to edit the value of this variable or remove calls to the sleep function on the script. +const SLEEP_DURATION = 0.1; +// Global variables should be initialized. +let api_key = "TODO_EDIT_THE_API_KEY"; + +export default function() { + group("/pet", () => { + let url = BASE_URL + `/pet`; + // Request No. 1 + // TODO: edit the parameters of the request body. + let body = {"id": "long", "category": {"id": "long", "name": "string"}, "name": "string", "photoUrls": "list", "tags": [{"id": "long", "name": "string"}], "status": "string"}; + let params = {headers: {"Content-Type": "application/json", "Accept": "application/json"}}; + let request = http.put(url, body, params); + sleep(SLEEP_DURATION); + + // Request No. 2 + // TODO: edit the parameters of the request body. + body = {"id": "long", "category": {"id": "long", "name": "string"}, "name": "string", "photoUrls": "list", "tags": [{"id": "long", "name": "string"}], "status": "string"}; + params = {headers: {"Content-Type": "application/json"}}; + request = http.post(url, body, params); + sleep(SLEEP_DURATION); + }); + group("/pet/findByStatus", () => { + let status = "TODO_EDIT_THE_STATUS"; + let url = BASE_URL + `/pet/findByStatus?status=${status}`; + // Request No. 1 + let request = http.get(url); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + }); + group("/pet/findByTags", () => { + let tags = "TODO_EDIT_THE_TAGS"; + let url = BASE_URL + `/pet/findByTags?tags=${tags}`; + // Request No. 1 + let request = http.get(url); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + }); + group("/pet/{petId}", () => { + let petId = "TODO_EDIT_THE_PETID"; + let url = BASE_URL + `/pet/${petId}`; + // Request No. 1 + let request = http.get(url); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + + // Request No. 2 + // TODO: edit the parameters of the request body. + body = {"name": "string", "status": "string"}; + params = {headers: {"Content-Type": "application/x-www-form-urlencoded"}}; + request = http.post(url, body, params); + sleep(SLEEP_DURATION); + + // Request No. 3 + params = {headers: {"api_key": `${api_key}`}}; + request = http.delete(url, params); + sleep(SLEEP_DURATION); + }); + group("/pet/{petId}/uploadImage", () => { + let petId = "TODO_EDIT_THE_PETID"; + let url = BASE_URL + `/pet/${petId}/uploadImage`; + // Request No. 1 + // TODO: edit the parameters of the request body. + let body = {"additionalMetadata": "string", "file": http.file(open("/path/to/file.bin", "b"), "test.bin")}; + let params = {headers: {"Content-Type": "multipart/form-data", "Accept": "application/json"}}; + let request = http.post(url, body, params); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + }); + group("/store/inventory", () => { + let url = BASE_URL + `/store/inventory`; + // Request No. 1 + let request = http.get(url); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + }); + group("/store/order", () => { + let url = BASE_URL + `/store/order`; + // Request No. 1 + // TODO: edit the parameters of the request body. + let body = {"id": "long", "petId": "long", "quantity": "integer", "shipDate": "date", "status": "string", "complete": "boolean"}; + let params = {headers: {"Content-Type": "application/json", "Accept": "application/json"}}; + let request = http.post(url, body, params); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + }); + group("/store/order/{orderId}", () => { + let orderId = "TODO_EDIT_THE_ORDERID"; + let url = BASE_URL + `/store/order/${orderId}`; + // Request No. 1 + let request = http.get(url); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + + // Request No. 2 + request = http.delete(url); + sleep(SLEEP_DURATION); + }); + group("/user", () => { + let url = BASE_URL + `/user`; + // Request No. 1 + // TODO: edit the parameters of the request body. + let body = {"id": "long", "username": "string", "firstName": "string", "lastName": "string", "email": "string", "password": "string", "phone": "string", "userStatus": "integer"}; + let params = {headers: {"Content-Type": "application/json", "Accept": "application/json"}}; + let request = http.post(url, body, params); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + }); + group("/user/createWithArray", () => { + let url = BASE_URL + `/user/createWithArray`; + // Request No. 1 + let params = {headers: {"Content-Type": "application/json", "Accept": "application/json"}}; + let request = http.post(url, params); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + }); + group("/user/createWithList", () => { + let url = BASE_URL + `/user/createWithList`; + // Request No. 1 + let params = {headers: {"Content-Type": "application/json", "Accept": "application/json"}}; + let request = http.post(url, params); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + }); + group("/user/login", () => { + let password = "TODO_EDIT_THE_PASSWORD"; + let username = "TODO_EDIT_THE_USERNAME"; + let url = BASE_URL + `/user/login?username=${username}&password=${password}`; + // Request No. 1 + let request = http.get(url); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + }); + group("/user/logout", () => { + let url = BASE_URL + `/user/logout`; + // Request No. 1 + let request = http.get(url); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + }); + group("/user/{username}", () => { + let username = "TODO_EDIT_THE_USERNAME"; + let url = BASE_URL + `/user/${username}`; + // Request No. 1 + let request = http.get(url); + check(request, { + "successful operation": (r) => r.status === 200 + }); + sleep(SLEEP_DURATION); + + // Request No. 2 + // TODO: edit the parameters of the request body. + body = {"id": "long", "username": "string", "firstName": "string", "lastName": "string", "email": "string", "password": "string", "phone": "string", "userStatus": "integer"}; + params = {headers: {"Content-Type": "application/json"}}; + request = http.put(url, body, params); + sleep(SLEEP_DURATION); + + // Request No. 3 + request = http.delete(url); + sleep(SLEEP_DURATION); + }); +}